mybatis中useGeneratedKeys用法--插入数据库后获取主键值

前言:今天无意在mapper文件中看到useGeneratedKeys这个词,好奇就查了下,发现能解决我之前插入有外键表数据时,这个外键获取繁琐的问题,于是学习敲DEMO记录

     在项目中经常需要获取到插入数据的主键来保障后续操作,数据库中主键一般我们使用自增或者uuid()的方式自动生成

问题:对于uuid使用Java代码生成的方式还比较容易控制,然而使用数据库生成的主键,这样我们就需要将插入的数据再查询出来得到主键,某些情况下还可能查询到多条情况,这样就比较尴尬了。

   那有什么办法来插入数据的时候就得到这个主键呢?

以下是Demo,分别定义了一个主键自增的表,一个uuid主键的表,对应实体Student,和UUidStudent分别说明两种情况下插入数据如何获取到主键值

一、自增对应实体Student

package com.ydcc.model;

public class Student
{

    private String id;
    private String name;
    private Integer age;

}

对应的mapper.xml如下

<mapper namespace="com.ydcc.mappers.StudentMapper">

    <resultMap type="Student" id="StudentResult">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="age" column="age"/>
    </resultMap>

    <insert id="add" parameterType="Student"  useGeneratedKeys="true" keyProperty="id" ><!--keyProperty对应的是实体中的属性不是数据库-->
        insert into t_student (name,age) values (#{name},#{age})
    </insert>

</mapper> 

二、uuid非自增对应实体:UUidStudent

package com.ydcc.model;

public class UUidStudent
{
    private String uuid;
    private String name;
    private int age;
}

对应的xml如下

<mapper namespace="com.ydcc.mappers.UUidStudentMapper">

    <resultMap type="Student" id="StudentResult">
        <id property="uuid" column="uuid"/>
        <result property="name" column="name"/>
        <result property="age" column="age"/>
    </resultMap>

    <insert id="add" parameterType="Student" useGeneratedKeys="true" keyProperty="uuid">
        <!-- 
     <selectKey resultType="String" order="BEFORE" keyProperty="uuid">    SELECT uuid() </selectKey> insert into t_uuidstudent (uuid,name,age) values (#{uuid},#{name},#{age})
    
--> <selectKey resultType="String" order="AFTER" keyProperty="uuid"> <!--keyProperty对应的是实体中的属性不是数据库-->   SELECT uuid() </selectKey> insert into t_uuidstudent (uuid,name,age) values ( uuid(), #{name},#{age}) </insert> </mapper>

来看以下测试代码和运行效果

package com.ydcc.service;


import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.ydcc.mappers.StudentMapper;
import com.ydcc.mappers.UUidStudentMapper;
import com.ydcc.model.Student;
import com.ydcc.model.UUidStudent;
import com.ydcc.util.SqlSessionFactoryUtil;

public class StudentTest2
{

    private static Logger logger = Logger.getLogger(StudentTest2.class);
    private SqlSession sqlSession = null;
    private StudentMapper studentMapper = null;
    private UUidStudentMapper uuidstudentMapper = null;

    /**
     * 测试方法前调用
     * 
     * @throws Exception
     */
    @Before
    public void setUp() throws Exception
    {
        sqlSession = SqlSessionFactoryUtil.openSession();
        studentMapper = sqlSession.getMapper(StudentMapper.class);
        uuidstudentMapper = sqlSession.getMapper(UUidStudentMapper.class);
    }

    /**
     * 测试方法后调用
     * 
     * @throws Exception
     */
    @After
    public void tearDown() throws Exception
    {
        sqlSession.close();
    }

    @Test
    public void testAdd()
    {
        logger.info("添加学生");

        Student student = new Student();
        student.setName("王五");
        student.setAge(12);

        studentMapper.add(student);

        logger.info("Student是:" + student.toString());
        sqlSession.commit();
    }

    @Test
    public void testAddUUidStudent()
    {
        logger.info("添加uuid学生");

        UUidStudent uuidStudent = new UUidStudent();
        uuidStudent.setName("uuid王五");
        uuidStudent.setAge(12);

        uuidstudentMapper.add(uuidStudent);

        logger.info("uuidStudent是:" + uuidStudent.toString());
        sqlSession.commit();
    }

}

  运行结果:

  [main] INFO com.ydcc.service.StudentTest2 - 添加uuid学生

  [main] INFO com.ydcc.service.StudentTest2 - uuidStudent是:UUidStudent [uuid=6885de71-c32d-11e8-88e1-0c9d920ff4e1, name=uuid王五, age=12]
  [main] INFO com.ydcc.service.StudentTest2 - 添加学生
  [main] INFO com.ydcc.service.StudentTest2 - Student是:Student [id=9, name=王五, age=12]

   经过与插入数据对比,发现数据无误,这里总结注意的点

  1、keyProperty对应的是实体中的属性,不是数据库字段

  2、对于非自增主键,必须显式写出     

  <selectKey resultType="java.lang.String" order="AFTER" keyProperty="uuid">

     SELECT uuid()

  </selectKey>

   order的设置,在insert sql语句执行前(BEFORE)或者执行后(AFTER),
  上面注释掉的代码用的before,看测试代码中我并没有对uuidStudent进行uuid set值,但是insert sql中缺用到#{uuid},理解为在执行前已经将主键id值赋给实体,直接取值就行.经过测试如果把#{uuid}换成uuid(),就发现得到的主键和入库的数据不一致
  使用after,可以看到使用了数据库的uuid(),那么在插入数据后,把这个值赋给了实体uuidStudent.

  3、对于自增的设计,我们直接用useGeneratedKeys="true" keyProperty="id"正常些插入语句即可

附上标签中几个字段的解释:




敲demo过程中因为用的电脑上之前的mysql-connector包,连接数据库时报Unknown character set index for field '255' received from server.的错,经查,因为是我本地用的mysql8的版本高、jar包版本低的原因
MYSQL 5.5 之前, UTF8 编码只支持1-3个字节;从MYSQL5.5开始,可支持4个字节UTF编码utf8mb4,升级下jar包就解决了



  

猜你喜欢

转载自www.cnblogs.com/yuandian8/p/9721555.html
今日推荐