今天遇到使用mybatis插入数据需要使用返回的自增id问题。
xml方法:记得加上useGeneratedKeys和keyProperty配置即可,前者是指设置是否使用jdbc的getGenereatedKeys方法获取主键并赋值到keyProperty设置的属性中,后者即实体类主键字段
在这里插入代码片
<insert id="insertUserInfo" parameterType="com.xxl.job.executor.entity.SysUserInfo" keyProperty="id" useGeneratedKeys="true" >
insert into t_user_info (uuid, name, password,user_no,user_name , name_en, email, department_id,department_name, title, id_card, sex, mobile, phone, status,other_departments,if_sync)
values (#{uuid},#{name},#{password},#{userNo},#{userName}, #{nameEn},#{email},#{departmentId},#{departmentName},#{title}, #{idCard},#{sex},#{mobile},#{phone},#{status},#{otherDepartments},#{ifSync})
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
select last_insert_id()
</selectKey>
调用的时候不是用
int id = dao.insertXXX;
而是直接用实体类的对象getId就可以了
比如:
UserInfo userInfo = new UserInfo();
XXXXX
userInfoDao.insert(userInfo );
System.out.println(userInfo.getId());
需要注意:
mapper中方法返回值要与mybatis中一致,不要加Param注解
Long insertUserInfo(SysUserInfo sysUser);