Mybatis?Plus插入數據后獲取新數據id值的踩坑記錄
問題描述:
Mybatis Plus的insert方法,按說插入數據后會自動返回id
mapper方法:
@DS("wxuser")
@Mapper
public interface UserInfoMapper extends BaseMapper<UserInfo> {
}
業(yè)務類:
@Autowired
UserInfoMapper userInfoMapper;
UserInfo user = new UserInfo();
user.setAddress(userInfo.getAddress());
user.setAge(userInfo.getAge());
user.setMobile(userInfo.getMobile());
user.setCreateTime(new Date());
user.setUpdateTime(new Date());
// 此num是指的插入數據成功的條數
int num = userInfoMapper.insert(user);
//如果想要獲取插入數據的id,需要:user.getUserId();
int id = user.getUserId();這樣按說是可以的,但是我這里仍然獲取不到,所以需要再修改。
解決方法:
修改后mapper類:
@DS("wxuser")
@Mapper
public interface UserInfoMapper extends BaseMapper<UserInfo> {
int saveUserInfo(@Param("userInfo")UserInfo userInfo);
}在resources目錄中新建mapper目錄,創(chuàng)建UserInfoMapper.xml文件:
注意三個值:
useGeneratedKeys=“true”
說明:允許 JDBC 支持自動生成主鍵,需要數據庫驅動支持。如果設置為 true,將強制使用自動生成主鍵。盡管一些數據庫驅動不支持此特性,但仍可正常工作(如 Derby)。
(僅適用于 insert 和 update)這會令 MyBatis 使用 JDBC 的 getGeneratedKeys 方法來取出由數據庫內部生成的主鍵(比如:像 MySQL 和 SQL Server 這樣的關系型數據庫管理系統(tǒng)的自動遞增字段),默認值:false。
keyProperty=“userInfo.userId”
說明:keyProperty中對應的值是實體類的屬性,而不是數據庫的字段
keyColumn=“userId”
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wx.user.mapper.UserInfoMapper">
<insert id="saveUserInfo" useGeneratedKeys="true" keyProperty="userInfo.userId" keyColumn="userId">
insert into userInfo (userNick,userName,password,isdelete,address,mobile) values (#{userInfo.userNick},#{userInfo.userName},#{userInfo.password},#{userInfo.isDelete},#{userInfo.address},#{userInfo.mobile})
</insert>
</mapper>
application.yml文件中:
# Mybatis Plus
mybatis-plus:
configuration:
map-underscore-to-camel-case: false # 設置字段不使用下劃線方式
global-config:
db-config:
id-type: AUTO
table-underline: false # 設置表名字不使用下劃線方式
mapper-locations: classpath*:/mapper/**/*.xml
修改后的業(yè)務類:
@Autowired
UserInfoMapper userInfoMapper;
UserInfo user = new UserInfo();
user.setAddress(userInfo.getAddress());
user.setAge(userInfo.getAge());
user.setMobile(userInfo.getMobile());
user.setCreateTime(new Date());
user.setUpdateTime(new Date());
// 此num是指的插入數據成功的條數
int num = userInfoMapper.saveUserInfo(user);
//如果想要獲取插入數據的id,需要:user.getUserId();
int id = user.getUserId();
這樣就可以獲取到新插入數據的id值了
總結
到此這篇關于Mybatis Plus插入數據后獲取新數據id值的文章就介紹到這了,更多相關Mybatis Plus獲取新數據id值內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot2.x漏洞將logback1.2.x 升級至1.3.x
安全部門在代碼漏洞掃描中發(fā)現logback 1.2.x版本存在CVE漏洞,建議升級至1.3.x版本,本文就來介紹了logback1.2.x 升級至1.3.x,具有一定的參考價值,感興趣的可以了解一下2024-09-09
SpringBoot v2.2以上重復讀取Request Body內容的解決方案
這篇文章主要介紹了SpringBoot v2.2以上重復讀取Request Body內容的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10
IDEA:Error running,Command line is too&n
這篇文章主要介紹了IDEA:Error running,Command line is too long.解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07

