mybatis再标签中添加什么属性可以将自增主键封装到对象里
时间: 2023-11-28 19:51:32 浏览: 31
在 MyBatis 中,可以使用 `<selectKey>` 标签来自动将自增主键封装到对象里。具体实现步骤如下:
1. 在插入数据的 SQL 语句中,需要添加 `useGeneratedKeys` 属性,用于告诉 MyBatis 使用数据库自动生成的主键。
例如:
```
<insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">
INSERT INTO user(name, age, email) VALUES(#{name}, #{age}, #{email})
</insert>
```
2. 在 `<insert>` 标签中添加 `<selectKey>` 标签,用于获取自动生成的主键并将其封装到对象中。
例如:
```
<insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">
<selectKey keyProperty="id" resultType="Long" order="AFTER">
SELECT last_insert_id()
</selectKey>
INSERT INTO user(name, age, email) VALUES(#{name}, #{age}, #{email})
</insert>
```
其中,`keyProperty` 属性指定了将自动生成的主键封装到哪个属性中,`resultType` 属性指定了主键的类型,`order` 属性指定了 `<selectKey>` 标签的执行顺序,`AFTER` 表示在插入语句执行之后执行 `<selectKey>` 标签。