在ssm框架里,我在xml里面<inser标签t执行SQL增加语句,该sql语句并没有设置增加信息的id,该id由mysql主键自动递增,我该如何获取我增加的这条信息的id。
时间: 2024-02-22 09:58:20 浏览: 87
在SSM框架中,可以通过两种方式获取新增记录的ID:
1. 在`<insert>`标签中添加`useGeneratedKeys="true" keyProperty="id"`属性,表示使用数据库自动生成的主键,并将其赋值给Java对象的id属性。例如:
```xml
<insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">
insert into user(username, password) values(#{username}, #{password})
</insert>
```
在执行该插入语句后,User对象的id属性即为新增记录的主键值。
2. 在`<insert>`标签中添加`selectKey`子元素,通过SQL语句查询新增记录的主键值,并将其赋值给Java对象的id属性。例如:
```xml
<insert id="insertUser" parameterType="User">
<selectKey resultType="int" keyProperty="id" order="AFTER">
select LAST_INSERT_ID()
</selectKey>
insert into user(username, password) values(#{username}, #{password})
</insert>
```
在执行该插入语句后,User对象的id属性即为新增记录的主键值。其中,`select LAST_INSERT_ID()`是MySQL特有的函数,用于获取最后一次插入的自增ID。
阅读全文
相关推荐













