2022-12-27
很多时候,在向数据库插入数据时,需要保留插入数据的 id,以便进行后续的 update 操作或者将 id 存入其他表作为外键。但在默认情况下,insert 操作返回的是一个 int 值,并不是表示主键 id,而是表示当前 SQL 语句影响的行数
接下来,我们看看 MyBatis 如何在使用 MySQL 和 Oracle 做 insert 插入操作时将返回的 id 绑定到对象中
1.1. MySQL 数据库
<insert id="insertAndGetId" useGeneratedKeys="true" keyProperty="userId" parameterType="com.chenzhou.mybatis.User"> insert into user(userName,password,comment) values(#{userName},#{password},#{comment}) </insert>
keyProperty:表示返回的 id 要保存到对象的哪个属性中,仅适用于 insert 和 update 语句
useGeneratedKeys:表示主键 id 为自增长模式,默认是 false,仅适用于 insert 和 update 语句
<insert id="insert" parameterType="com.test.User"> <selectKey resultType="INTEGER" order="BEFORE" keyProperty="userId"> SELECT SEQ_USER.NEXTVAL as userId from DUAL </selectKey> insert into user (user_id, user_name, modified, state) values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{modified,jdbcType=TIMESTAMP}, #{state,jdbcType=INTEGER}) </insert>
摘自 https://blog.csdn.net/weixin_38192427/article/details/125259894