mybatis新增save结束后自动返回主键id详解

网友投稿 2497 2022-11-17

mybatis新增save结束后自动返回主键id详解

mybatis新增save结束后自动返回主键id详解

目录mybatis新增save结束后自动返回主键id1.使用场景2.原理在Mybatis配置了mybatis或者mybatis-plus中save方法返回主键值1.mapper.xml中2.service或者dao中

mybatis新增save结束后自动返回主键id

1.使用场景

save操作之前实体类中id为null,save之后自动返回带id的实体类

@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 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配置了

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}

)

mybatis或者mybatis-plus中save方法返回主键值

1.mapper.xml中

方式:

useGeneratedKeys=“true” keyProperty=“id” keyColumn=“id”

解释:

http://

在xml中定义useGeneratedKeys为true,返回主键id的值,keyColumn和keyProperty分别代表数据库记录主键字段和java对象成员属性

useGeneratedKeys="true" keyProperty="id" keyColumn="id">

INSERT INTO adjust_bill_info(external_bill_id, warehouse_code, warehouse_name)

VALUES(#{externalBillId}, #{warehouseCode}, #{warehouseName});

useGeneratedKeys="true" keyProperty="id" keyColumn="id">

INSERT INTO adjust_bill_info(external_bill_id, warehouse_code, warehouse_name)

VALUES(#{externalBillId}, #{warehouseCode}, #{warehouseName});

2.service或者dao中

注意:通过该种方式得到的结果是受影响的行数!!!!!

如果要获取主键id值,需要从传入的对象中获取!!!!!

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());

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:艾瑞咨询:2020年中国容器云市场研究报告
下一篇:laydate 时间选中后触发函数
相关文章

 发表评论

暂时没有评论,来抢沙发吧~