小編給大家分享一下mybatis如何實現新增save結束后自動返回主鍵id,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
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<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);
}
}
}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>方式:
useGeneratedKeys=“true” keyProperty=“id” keyColumn=“id”
解釋:
在xml中定義useGeneratedKeys為true,返回主鍵id的值,keyColumn和keyProperty分別代表數據庫記錄主鍵字段和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>注意:通過該種方式得到的結果是受影響的行數?。。。?!
如果要獲取主鍵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());
以上是“mybatis如何實現新增save結束后自動返回主鍵id”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。