MySQL insert into添加数据并返回该条数据的id的方法

在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
开始查询
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值