mybatis新增save结束后自动返回主键id详解
这篇文章主要介绍了mybatis新增save结束后自动返回主键id详解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
目录
mybatis新增save结束后自动返回主键id
1.使用场景
2.原理在Mybatis配置了
mybatis或者mybatis-plus中save方法返回主键值
1.mapper.xml中
2.service或者dao中
mybatis新增save结束后自动返回主键id
1.使用场景
save操作之前实体类中id为null,save之后自动返回带id的实体类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | @Override public ChartPagePanel save(ChartPagePanel entity) { UserDetails user = SecurityContextHolder.getUserDetails(); entity.setCreateUser(user.getUsername()); entity.setLastModifyUser(user.getUsername()); //entity中的id为null chartPagePanelMapper.save(entity); //经过save操作后自动返回带id的entity // savePanelManage(entity); 其中的entity带有id savePanelManage(entity); return entity; } @Transactional public void savePanelManage(ChartPagePanel entity){ if (entity.getChartPageManges()!= null && entity.getChartPageManges().size()> 0 ) { Map<String, Object> map = new HashMap<>(); for ( int i = 0 ; i < entity.getChartPageManges().size(); i++) { int manageId = entity.getChartPageManges().get(i).getId(); map.put( "manageId" , manageId); map.put( "panelId" , entity.getId()); chartPagePanelManageMapper.save(map); } } } |
2.原理在Mybatis配置了
1 | useGeneratedKeys=“true” keyProperty=“id” |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | < insert id = "save" parameterType = "com.centrin.generator.entity.ChartPagePanel" useGeneratedKeys = "true" keyProperty = "id" > insert into chart_page_panel ( `parent_id`, `position`, `name`, `create_time`, `create_user`, `last_modify_time`, `last_modify_user` ) values ( #{parentId}, #{position}, #{name}, NOW(), #{createUser}, NOW(), #{lastModifyUser} ) </ insert > |
mybatis或者mybatis-plus中save方法返回主键值
1.mapper.xml中
方式:
1 | useGeneratedKeys=“true” keyProperty=“id” keyColumn=“id” |
解释:
在xml中定义useGeneratedKeys为true,返回主键id的值,keyColumn和keyProperty分别代表数据库记录主键字段和java对象成员属性名
1 2 3 4 5 | < insert id = "saveBill" parameterType = "com.jd.fp.mrp.domain.model.biz.AdjustBillInfo" useGeneratedKeys = "true" keyProperty = "id" keyColumn = "id" > INSERT INTO adjust_bill_info(external_bill_id, warehouse_code, warehouse_name) VALUES(#{externalBillId}, #{warehouseCode}, #{warehouseName}); </ insert > |
2.service或者dao中
注意:通过该种方式得到的结果是受影响的行数!!!!!
如果要获取主键id值,需要从传入的对象中获取!!!!!
1 2 | Long id = aTranscationMapper.saveBill(adjustBillInfo); System.out.println( "===========保存受影响的行数:" +id+ " 保存的id值为:" +adjustBillInfo.getId()); |
输出结果展示:
===========保存受影响的行数:1 保存的id值为:191
mybatis-plus的insert后,返回主键id,直接通过传入的对象获取id即可!
bizApplicationFormMapper.insert(form);
System.out.println("=============="+form.getId());
以上为个人经验,希望能给大家一个参考
原文链接:https://blog.csdn.net/xy405580364/article/details/102837263