• mybatis返回主键ID(自增和非自增)的两种方式


    一.mapper映射文件

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
      PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.mybatis.mapper.TableNameMapper">
        <!-- 插入数据并返回自增ID
            有自增ID功能数据库可以采用useGeneratedKeys="true"开启判断是否是自增ID
             keyProperty="id"  指定插入数据后自增ID返回时赋值给实体类的那个属性(这里是id属性)
         -->
        <insert id="insertData"  parameterType="java.util.HashMap" useGeneratedKeys="true" keyProperty="id">
            insert into tableName values(null,#{name})
        </insert>
        <!-- 
            非自增主键
            像Oracle数据库采用序列来作为自增主键,通过 selectKey子来获取主键值
            MySQL同样适用(只是order属性处为after, 因为mysql自增完ID后才返回ID值)
         -->
         <insert id="insertDataAgain">
             <!-- 
                 selectKey中resultType属性指定期望主键的返回的数据类型,
                 keyProperty属性指定实体类对象接收该主键的字段名
                 order属性指定执行查询主键值SQL语句是在插入语句执行之前还是之后(可取值:after和before)
              -->
              <!-- oracle -->
             <selectKey resultType="integer" keyProperty="id" order="BEFORE">
                 SELECT LAST_INSERT_ID()
             </selectKey>
             <!--
             <selectKey resultType="integer" keyProperty="id" order="AFTER">
                 SELECT id from tableName order by id desc limit 1
             </selectKey>
             -->
            insert into tableName values(null,#{name})
        </insert>
    </mapper>

    注: ORACLE返回主键最好是在插入SQL执行之前执行,也就是order属性值设置为before

    二.mapper接口

    public interface TableNameMapper {
        //插入数据
        public Integer insertData(Map<String, Object> map);
        //插入数据
        public Integer insertDataAgain(Map<String, Object> map);
    }

    三.如何取到ID

        当数据添加成功之后,你打印接口中传入的map,会发现里面多了一个id属性,且值和数据库自增的id是一模一样的,这就是ID返回的实现

  • 相关阅读:
    perf + 火焰图用法 小结
    忽略多年的地理基本知识
    windows7安装docker异常:looks like something went wrong in step ‘looking for vboxmanage.exe’
    我的选择
    CSS3 width的min/max-content、fill-available以及fit-content
    Redis入门与命令汇总
    javascript中的原型详解
    Promise实现及原理
    nodejs中的垃圾回收
    javascript中的闭包
  • 原文地址:https://www.cnblogs.com/KdeS/p/13522567.html
Copyright © 2020-2023  润新知