MyBatis主键返回

  • Post author:
  • Post category:其他


这篇文章介绍了MyBatis的主键返回方法




一.需求分析

当我们表的主键设置为自增,且插入数据后需要主键id时,就要使用主键返回的方法,来获取当前插入数据的主键。

表如下:

在这里插入图片描述



二.主键返回



1.使用selectKey 标签

< selectKey >标签,keyProperty:设置为目标属性,resultType:设置返回值类型,order:值为after,before

after: sql之后执行,before: sql之前执行

示例:

StudentMapper接口

public interface StudentMapper {
    int insert(Student student);
}

StudentMapper.xml代码

    <insert id="insert" parameterType="com.hem.pojo.Student">
        <selectKey keyProperty="id" resultType="int" order="AFTER">
            select last_insert_id()
        </selectKey>
        insert into student (name,email,age)
        values (#{name},#{email},#{age});
    </insert>

test代码:

    @Test
    public void testInsert() throws IOException {
        //使用文件流读取核心配置文件SqlMapConfig.xml
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //创建SqlSessionFactory工厂
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //取出sqlSession对象
        SqlSession sqlSession = factory.openSession();
        //完成查询操作
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        Student student = new Student("小白","12321",99);
        int num = studentMapper.insert(student);
        System.out.println(student.getId());
        sqlSession.commit();
        //关闭sqlSession
        sqlSession.close();
    }

测试结果:

在这里插入图片描述



2. 设置< insert >便签的属性

设置 useGeneratedKeys=”true”,然后再把 keyProperty 设置为目标属性就 OK 了

示例:

StudentMapper接口

public interface StudentMapper {
    int insert(Student student);
}

StudentMapper.xml代码:

<insert id="insert" parameterType="com.hem.pojo.Student" useGeneratedKeys="true" keyProperty="id">
        insert into student (name,email,age)
        values (#{name},#{email},#{age});
    </insert>

test代码:

    @Test
    public void testInsert() throws IOException {
        //使用文件流读取核心配置文件SqlMapConfig.xml
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //创建SqlSessionFactory工厂
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //取出sqlSession对象
        SqlSession sqlSession = factory.openSession();
        //完成查询操作
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        Student student = new Student("小白","12321",99);
        int num = studentMapper.insert(student);
        System.out.println(student.getId());
        sqlSession.commit();
        //关闭sqlSession
        sqlSession.close();
    }

测试结果:

在这里插入图片描述

在这里插入图片描述

202210161704日



版权声明:本文为qq_53843555原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。