前言
今天在使用MyBatis的时候插入了一条数据,记得增加上这段配置(这里展示MyBatis的注解形式)可以获取到插入数据库中这条数据的id值,但是返回的int id 为1。实际检查数据库中是插入成功了,并且id值也是正确的。
@Options(useGeneratedKeys = true, keyProperty = "id")
所以去测试了一下,详细记录一下。
下面分别展示注解开发,和xml映射的两种方式代码。
业务代码:
Integer id = tblSchoolOrganizationInfoMapper.insertReturnId(info);
id = info.getId();
log.info("插入成功!id = {}", id);
注解开发代码:
@Mapper
public interface TblSchoolOrganizationInfoMapper extends BaseMapper<TblSchoolOrganizationInfo> {
@Insert("INSERT INTO TblSchoolOrganizationInfo(`createTime`, `isDeleted`, `updateTime`, `code`, `name`, `remarks`, `theOrder`, `childNum`, `isLeaf`, `parentId`, `theLevel`, `trainingScope`, `allNodesName`, `rootId`, `secondNodeId`, `account`) " +
"VALUES(#{createtime},#{isdeleted},#{updatetime},#{code},#{name},#{remarks},#{theorder},#{childnum},#{isleaf},#{parentid},#{thelevel},#{trainingscope},#{allnodesname},#{rootid},#{secondnodeid},#{account})")
@Options(useGeneratedKeys = true, keyProperty = "id")
Integer insertReturnId(TblSchoolOrganizationInfo info);
}
xml形式:
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.*******.mapper.TblSchoolOrganizationInfoMapper">
<!-- todo sql语句赋值 同注解开发一样 功能实现 -->
<insert id="insertReturnId" useGeneratedKeys="true" keyProperty="id">
INSERT INTO TblSchoolOrganizationInfo
(`createTime`, `isDeleted`, `updateTime`, `code`, `name`, `remarks`, `theOrder`, `childNum`, `isLeaf`, `parentId`, `theLevel`, `trainingScope`, `allNodesName`, `rootId`, `secondNodeId`, `account`)
VALUES
(#{createtime}, #{isdeleted}, #{updatetime}, #{code}, #{name}, #{remarks}, #{theorder}, #{childnum}, #{isleaf}, #{parentid}, #{thelevel}, #{trainingscope}, #{allnodesname}, #{rootid}, #{secondnodeid}, #{account})
</insert>
</mapper>
注意事项:
1.需要注意插入的表主键要设置主键递增,AUTO_INCREMENT。
2.不管是哪种形式,记得加上
//注解形式
@Options(useGeneratedKeys = true, keyProperty = "id")
//xml形式
<insert id="insertReturnId" useGeneratedKeys="true" keyProperty="id">
否则即是添加功能正常但是你返回的id值不正确,是一串很大的负数值如-759160831
3.在编写两种形式的SQL时不要进行添加id值,不写就行。否则可能造成添加后,id值是一串很大的值。
4.在你正确编写好sql后,在你的控制类调用方法这里注意一下,一个误区,时间长没用我也中招了,这样返回来的id实际是返回的是影响的行数!!!所以说比如我这个情况,返回回来的就是1.
但是MyBatis会将你添加成功的对象赋值给你现有的对象中,所以获取id可以直接get一下原来的对象,即可获得正确的id值。
实际应该是这样
Integer id = tblSchoolOrganizationInfoMapper.insertReturnId(info);
log.info("插入成功!影响的行数 row = {}", id);
id = info.getId();
log.info("插入成功!id = {}", id);
其实是一个很简单的问题,但是容易记错。