MyBatis和Mongodb插入数据,自动返回生成的主键id到实体类
一、Mybatis 是无法自动返回生成的主键id到实体类,需要另外配置:
正常情况下:
<insert id="insert" parameterType="Student" >insert into student(name, age) VALUES (#{name} , #{age})
</insert>
方案1:
配置 useGeneratedKeys 和 keyProperty
例如:
<insert id="insert" parameterType="Student" useGeneratedKeys="true" keyProperty="sid">insert into student(name, age) VALUES (#{name} , #{age})
</insert>
说明:
1、useGeneratedKeys=“true” 设置是否使用JDBC的getGeneratedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中.
2、keyProperty=“sid” 表示将自增长后的 Id 赋值给实体类中的 sid 字段。
方案2:
在 insert 标签中编写 selectKey 标签
<insert id="insert" parameterType="Student">insert into student(name, age) VALUES (#{name} , #{age})<selectKey keyProperty="sid" order="AFTER" resultType="int">SELECT LAST_INSERT_ID()</selectKey>
</insert>
说明:
1、< insert> 标签中没有 resultType 属性,但是 < selectKey> 标签是有的。
2、order=“AFTER” 表示先执行插入语句,之后再执行查询语句。
3、keyProperty=“sid” 表示将自增长后的 Id 赋值给 parameterType 指定的对象中的 sid 字段。
4、SELECT LAST_INSERT_ID() 表示 MySQL 语法中查询出刚刚插入的记录自增长 Id。5、resultType:指定 SELECTLAST_INSERT_ID() 的结果类型。
二、如果使用Mybatis-plus,insert是会自动返回主键id去实体类中。
三、Mongodb中MongoTemplate也是会自动返回主键id去实体类中。