insert
<insert id="insertUser" parameterType="com.imooc.mybatis.model.User">
INSERT INTO imooc_user(id,username,age,score) VALUES (#{id},#{username},#{age},#{score})
</insert>
insert属性
属性 | 描述 |
---|---|
id | 在命名空间中的唯一标识符 |
parameterType | 语句的参数类型,默认可选,MyBatis 会自动推断 |
flushCache | 设置为 true 后,只要语句被调用,都会导致本地缓存和二级缓存被清空,默认为 false |
timeout | 设置超时时间 |
statementType | STATEMENT,PREPARED 或 CALLABLE 中的一个,默认为 PREPARED(预处理) |
useGeneratedKeys | 取出由数据库自动生成的主键,仅对支持主键自动生成的数据库有效,默认为 false |
keyProperty | 主键的名称,必须与useGeneratedKeys 一起使用,默认未设置 |
返回主键
自增主键
1.xml方式
如果使用的数据库,如 MySQL,PostgreSQL,这些数据库支持自增主键,那么得到返回的主键只需添加上 useGeneratedKeys 和 keyProperty 两个属性即可。如下:
<insert id="insertUserNoId" useGeneratedKeys="true" keyProperty="id"
parameterType="com.imooc.mybatis.model.User">
INSERT INTO imooc_user(username,age,score) VALUES (#{username},#{age},#{score})
</insert>
在 insertUserNoId 中,我们并未添加上 id 参数,而是使用了数据库自增主键的特性,keyProperty 属性值对应 id 字段的名称,这样当语句执行成功后,对象的 id 字段会被自动设置为返回的 id 值。
2.注解方式
使用下面的注解方式,同样可以实现同样的效果:
@Insert("INSERT INTO imooc_user(username,age,score) VALUES (#{username},#{age},#{score})")
@Options(useGeneratedKeys = true, keyProperty = "id")
int insertUser(User user);
MyBatis 提供了 Options 注解来指定方法调用的行为。
selectKey标签
xml方式
如果数据库不支持主键自增,如 Oracle,MyBatis 提供了 selectKey 标签来通过 SQL 语句获得主键。
例如:
<insert id="insertUserNoId" parameterType="com.imooc.mybatis.model.User">
INSERT INTO imooc_user(username,age,score) VALUES (#{username},#{age},#{score})
<selectKey keyColumn="id" resultType="long" keyProperty="id" order="AFTER">
SELECT LAST_INSERT_ID()
</selectKey></insert>
selectKey 标签必须在 insert 标签里面,selectKey 有 4 个属性,它们的作用如下表:
属性 | 描述 |
---|---|
keyColumn | 数据库字段名,对应返回结果集中的名称 |
keyProperty | 目标字段名称,对应Java 对象的字段名 |
resultType | id字段的类型 |
order | 执行的顺序,在 insert 之前调用为 BEFORE,之后为 AFTER |
注意,selectKey 中的语句其实就是 SQL 语句,不同数据库得到主键的语句均不一样。
2.注解方式·
@Insert("INSERT INTO imooc_user(username,age,score) VALUES (#{username},#{age},#{score})")
@SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "id", before = false,
resultType = Long.class)
int insertUser(User user);
selectKey 也有相应的注解,不过配置属性略有不同,statement 属性对应标签中的 SQL 语句,而 before 属性则对应标签中的 order 属性,若 before 为 false,则 order 对应为 AFTER。