mybatis新增save結束后自動返回主鍵id詳解
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);
//經(jīng)過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配置了
useGeneratedKeys=“true” keyProperty=“id”
<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中
方式:
useGeneratedKeys=“true” keyProperty=“id” keyColumn=“id”
解釋:
在xml中定義useGeneratedKeys為true,返回主鍵id的值,keyColumn和keyProperty分別代表數(shù)據(jù)庫記錄主鍵字段和java對象成員屬性名
<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中
注意:通過該種方式得到的結果是受影響的行數(shù)!?。。?!
如果要獲取主鍵id值,需要從傳入的對象中獲取?。。。?!
Long id = aTranscationMapper.saveBill(adjustBillInfo);
System.out.println("===========保存受影響的行數(shù):"+id+" 保存的id值為:"+adjustBillInfo.getId());
輸出結果展示:
===========保存受影響的行數(shù):1 保存的id值為:191
mybatis-plus的insert后,返回主鍵id,直接通過傳入的對象獲取id即可!
bizApplicationFormMapper.insert(form);
System.out.println("=============="+form.getId());
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
spring-mvc/springboot使用MockMvc對controller進行測試
這篇文章主要介紹了spring-mvc/springboot使用MockMvc對controller進行測試,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11
HttpUtils 發(fā)送http請求工具類(實例講解)
下面小編就為大家?guī)硪黄狧ttpUtils 發(fā)送http請求工具類(實例講解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-07-07
springboot接口返回數(shù)據(jù)類型全面解析
這篇文章主要介紹了springboot接口返回數(shù)據(jù)類型問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12
使用Java代碼實現(xiàn)RocketMQ的生產(chǎn)與消費消息
這篇文章介紹一下其他的小組件以及使用Java代碼實現(xiàn)生產(chǎn)者對消息的生成,消費者消費消息等知識點,并通過代碼示例介紹的非常詳細,對大家的學習或工作有一定的幫助,需要的朋友可以參考下2024-07-07

