在Mapper.xml中写SQL语句时添加
1)insert按如下修改,添加属性 “useGeneratedKeys”和“keyProperty”,其中 keyProperty 是 Java 对象的属性名,而不是表格的字段名,通过该对象例如:keyword.getId()获取:
<insert id="add" useGeneratedKeys="true" keyProperty="id">
insert into keybiao(name, type, time) values (#{name},#{type},#{time})
</insert>
2)插入selectKey标签,获取同上
<insert id="add">
<!--selectKey 会将 SELECT LAST_INSERT_ID()的结果放入到传入的model的主键里面,
keyProperty 对应的model中的主键的属性名,这里是 user 中的id,因为它跟数据库的主键对应
order AFTER 表示 SELECT LAST_INSERT_ID() 在insert执行之后执行,多用与自增主键,
BEFORE 表示 SELECT LAST_INSERT_ID() 在insert执行之前执行,这样的话就拿不到主键了,
这种适合那种主键不是自增的类型
resultType 主键类型 -->
<selectKey resultType="java.lang.Long" order="AFTER" keyProperty="id">
select last_insert_id();
</selectKey>
insert into keybiao(name, type, time) values (#{name},#{type},#{time})
</insert>
``
在service层或controller层可以获取id
service层:
public String add(Keyword keyword) {
System.out.println("添加开始");
final Integer add = keywordMapper.add(keyword);
System.out.println("添加的返回的id:"+keyword.getId());
if (add>0){
System.out.println("end");
return "success";
}
return null;
}
controller层:
public String add(Keyword keyword){
keywordService.add(keyword);
System.out.println("添加的数据的id:"+keyword.getId());
return "redirect:/key/list";
}
结果
添加开始
17:01:14.587 [http-nio-8080-exec-9] DEBUG org.mybatis.spring.SqlSessionUtils - Creating SqlSession with JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@50d524e]
17:01:14.587 [http-nio-8080-exec-9] DEBUG java.sql.Connection - ooo Connection Opened
17:01:14.587 [http-nio-8080-exec-9] DEBUG o.m.s.t.SpringManagedTransaction - JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@50d524e] will not be managed by Spring
17:01:14.587 [http-nio-8080-exec-9] DEBUG org.mybatis.spring.SqlSessionUtils - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@295fbf25] was not registered for synchronization because synchronization is not active
17:01:14.589 [http-nio-8080-exec-9] DEBUG java.sql.PreparedStatement - ==> Executing: insert into keybiao(name, type, time) values (?,?,?)
17:01:14.589 [http-nio-8080-exec-9] DEBUG java.sql.PreparedStatement - ==> Parameters: 张三(String), 灵剑宗(String), 2021-07-28 00:00:00.0(Timestamp)
17:01:14.744 [http-nio-8080-exec-9] DEBUG org.mybatis.spring.SqlSessionUtils - Closing no transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@295fbf25]
添加的返回的id:133
end
添加的数据的id:133
开始查询