从Mapper中获取获取自动生成的主键

目录

1 前言

2 方法

2.1 改动动态SQL

2.2 在服务层中使用生成的主键


1 前言

我们往数据库中插入了一条数据,现在我们需要获取其自动生成的主键值,其中动态SQL如下:

<?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="xxx"><insert id="insert"><!--SQL语句--></insert>
</mapper>

接下来我将就这个例子,讲解如何获取自动生成的主键。

2 方法

2.1 改动动态SQL

向标签中多添加useGeneratedKeys和keyProperty,其中useGeneratedKeys="true"表示是否需要获取自动生成的主键,keyProperty="id"表示自动生成的主键赋值给传送过来实体类的id属性。

<insert id="insert" useGeneratedKeys="true" keyProperty="id">
</insert>

2.2 在服务层中使用生成的主键

@Service
public class ServiceImpl implements Service {public void func(xxx) {hMapper.insert(xx);Long id = dish.getId();//其它代码...}
}