当前位置: 首页 > news >正文

Java的dto,和多表的调用

1理论

需求是新增菜品eg:菜名:豆腐脑;口味:甜口,咸口,

菜单表:dish;口味表dish_flavor;

1dto:数据传输对象

新建一个dishDto对象有两个表里的属性

2用到两个表,dish,dish_flavor

flavors返回的是口味的集合,它属于dish_flavor表。1是豆腐脑,多是甜口,咸口。

2代码实现:

1建一个dishDto的对象,包含了两个表里用到的属性。

@Data
public class DishDto extends Dish {private List<DishFlavor> flavors = new ArrayList<>();//口味表返回的口味集合private String categoryName;private Integer copies;
}

2在dish的service接口层写保存新增菜品的方法。

3在它的实现类里实现该方法saveWithFlavor(DishDto dishDto)

在菜品DishServiceImpl里注入口味的DishFlavorService;

@Autowired

private DishFlavorService dishFlavorService;

有多表操作,用了事务,@Transactional,要在启动类里加@EnableTransactionManagement激活

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {//多张表的操作,加入事务控制@Autowiredprivate DishFlavorService dishFlavorService;/*** 新增菜品同时保存口味数据** @param dishDto*/@Override@Transactionalpublic void saveWithFlavor(DishDto dishDto) {
//保存菜品的基本信息到菜品表dish,this.save(dishDto);Long dishId = dishDto.getId();//菜品的idList<DishFlavor> flavors = dishDto.getFlavors();//菜品口味
//        处理元素并赋值flavors = flavors.stream().map((item) -> {item.setDishId(dishId);return item;}).collect(Collectors.toList());//java8新特性stream流的使用//保存菜品口味数据到菜品口味表dish_flavor}
}

4Controller层

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {@Autowiredprivate DishService dishService;@Autowiredprivate DishFlavorService dishFlavorService;@PostMappingpublic R<String> save(@RequestBody DishDto dishDto){//dto对象dishService.saveWithFlavor(dishDto);//调用事务方法return R.success("新增菜品成功");}

总结:

多表调用,建立dto,返回口味数据用集合接收,遍历口味,赋值给菜品。具体实现在业务层写了,也可以在sql里写。

http://www.lryc.cn/news/483358.html

相关文章:

  • 时序数据库TimescaleDB安装部署以及常见使用
  • MG算法(英文版)题解
  • 2-UML概念模型测试
  • 人工智能(AI)对于电商行业的变革和意义
  • 智能病历xml提取
  • RK3568平台开发系列讲解(GPIO篇)GPIO的sysfs调试手段
  • 使用 Web Search 插件扩展 GitHub Copilot 问答
  • workerman的安装与使用
  • QtQuick.Controls 控件介绍(都有哪些type)
  • Unity导出APK加速与导出失败总结(不定时更新)
  • 域名绑定服务器小白教程
  • 用 Collections.synchronizedSet 创建线程安全的 HashSet
  • 【深度学习】模型参数冻结:原理、应用与实践
  • 数字后端教程之Innovus report_property和get_property使用方法及应用案例
  • JS中console对象内部提供调试方法
  • python设计模式
  • 机器学习 笔记
  • 江协科技之STM32驱动1.3寸/0.96寸/0.91寸OLED显示屏介绍
  • Spring Security 认证流程,长话简说
  • 74HC245
  • Java的static关键字和静态代码块
  • Apex 批处理将 account owner 转移,同时实现关联的 opp 和 case 转移
  • Python | Leetcode Python题解之第557题反转字符串中的单词III
  • Spring设计模式
  • 信号保存和信号处理
  • 网站小程序app怎么查有没有备案?
  • 如何利用宏和VBA来提高文档编辑排版速度?
  • Kafka - 启用安全通信和认证机制_SSL + SASL
  • c++基础32输入和输出
  • [C++] 函数详解