插入数据并返回主键这种需求很常见,所以列出来。
一、实现方式
1. 使用useGeneratedKeys+keyProperty (推荐)
简单来说就是配置:
<insert id="" useGeneratedKeys="true" keyProperty="id">
将插入的ID赋值给设置的keyProperty对象属性字段里面,一般也就是对象的ID,比如插入User对象,设置赋值主键ID给id字段。
2. 使用selectKey
MySQL 数据库可以使用如下方式。
<selectKey keyProperty="id" resultType="int" order="AFTER">
SELECT LAST_INSERT_ID()
</selectKey>
二、具体演示:
基于上篇文章的代码新增:
package cn.saytime.mapper;
import cn.saytime.domain.User;
import java.util.List;
/**
* @author L
* @ClassName cn.saytime.mapper.UserMapper
* @Description
*/
public interface UserMapper {
/**
* 保存用户,返回主键,形式1
* @param user
*/
int saveReturnPK1(User user);
/**
* 保存用户,返回主键,形式2
* @param user
*/
int saveReturnPK2(User user);
}
<?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="cn.saytime.mapper.UserMapper" >
<!-- 增,返回主键 形式1 -->
<insert id="saveReturnPK1" parameterType="cn.saytime.domain.User" useGeneratedKeys="true" keyProperty="id">
INSERT INTO `test`.`tb_user`(`username`, age) VALUES(#{username}, #{age})
</insert>
<!-- 增,返回主键 形式2 -->
<insert id="saveReturnPK2" parameterType="cn.saytime.domain.User">
<selectKey keyProperty="id" resultType="int" order="AFTER">
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO `test`.`tb_user`(`username`, age) VALUES(#{username}, #{age})
</insert>
</mapper>
测试:
import cn.saytime.domain.User;
import cn.saytime.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Created by L on 2018/1/3.
*/
public class TestUserMapper {
SqlSessionFactory sqlSessionFactory = null;
SqlSession sqlSession = null;
UserMapper userMapper = null;
@Before
public void before(){
// mybatis 配置文件地址
String resource = "mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
// 加载配置文件,并构建sqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取sqlSession对象
sqlSession = sqlSessionFactory.openSession();
userMapper = sqlSession.getMapper(UserMapper.class);
}
@After
public void after(){
if(sqlSession != null){
// 注意这里的commit,否则提交不成功
sqlSession.commit();
sqlSession.close();
}
}
/**
* 测试保存用户返回主键,注意返回的主键塞到了插入对象user的id中
*/
@org.junit.Test
public void testSaveReturnPK(){
// 形式1
User user1 = new User();
user1.setUsername("李四");
user1.setAge(18);
int c1 = userMapper.saveReturnPK1(user1);
System.out.println("新增用户李四,返回主键:" + user1.getId() + " 操作数量:" + c1);
// 形式2
User user2 = new User();
user2.setUsername("王五");
user2.setAge(19);
int c2 = userMapper.saveReturnPK1(user2);
System.out.println("新增用户王五,返回主键:" + user2.getId() + " 操作数量:" + c2);
}
}
新增用户李四,返回主键:3 操作数量:1
新增用户王五,返回主键:4 操作数量:1
再次注意这里UserMapper.saveResultPK返回之后的数字仍然是操作数量,主键在User对象里面的id。