mybatis 主键自动生成
首先,如果你的数据库支持自动生成主键的字段(比如 MySQL 和 SQL Server) ,那么 你可以设置 useGeneratedKeys=”true”,而且设置 keyProperty 到你已经做好的目标属性上。 例如,如果上面的 Author 表已经对 id 使用了自动生成的列类型,那么语句可以修改为:
<insert id="insertAuthor" useGeneratedKeys="true" keyProperty="autyhorId"><!-- 加上这两个就OK了,keyProperty的值是主键名称-->
insert into Author (username,password,email,bio)
values (#{username},#{password},#{email},#{bio})
</insert>
MyBatis 有另外一种方法来处理数据库不支持自动生成类型,或者可能 JDBC 驱动不支 持自动生成主键时的主键生成问题。
这里有一个简单(甚至很傻)的示例,它可以生成一个随机 ID(可能你不会这么做, 但是这展示了 MyBatis 处理问题的灵活性,因为它并不真的关心 ID 的生成):
<insert id="insertAuthor">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
select CAST(RANDOM()*1000000 as INTEGER) a from SYSIBM.SYSDUMMY1
</selectKey>
insert into Author
(id, username, password, email,bio, favourite_section)
values
(#{id}, #{username}, #{password}, #{email}, #{bio}, #{favouriteSection,jdbcType=VARCHAR})
</insert>
| useGeneratedKeys | ( 仅 对 insert, update 有 用 ) 这 会 告 诉 MyBatis 使 用 JDBC 的 getGeneratedKeys 方法来取出由数据(比如:像 MySQL 和 SQL Server 这样的数据库管理系统的自动递增字段)内部生成的主键。 默认值:false。 |
| keyProperty | (仅对 insert, update 有用) 标记一个属性, MyBatis 会通过 getGeneratedKeys 或者通过 insert 语句的 selectKey 子元素设置它的值。 默认: 不设置。 Can be a comma separated list of property names if multiple generated columns are expected. |
当mybatis使用注解时:
/**
* 保存 id是主键
* @param user
*/
@Insert("insert into user(username,password,age) values(#{username},#{password},#{age})")
@Options(useGeneratedKeys = true, keyProperty = "id")
public void saveUser(User user);
浙公网安备 33010602011771号