通过修改sql映射文件,可以将mysql自增主键返回:
<insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
select LAST_INSERT_ID()
selectKey>
insert into user(username,birthday,sex,address)
values(#{username},#{birthday},#{sex},#{address});
insert>
添加selectKey实现将主键返回
keyProperty:返回的主键存储在pojo中的哪个属性
order:selectKey的执行顺序,是相对与insert语句来说,由于mysql的自增原理执行完insert语句之后才将主键生成,所以这里selectKey的执行顺序为after
resultType:返回的主键是什么类型
LAST_INSERT_ID():是mysql的函数,返回auto_increment自增列新记录id值。
需要增加通过select uuid()得到uuid值
keyProperty="id">
select uuid()
insert into user(id,username,birthday,sex,address)
values(#{id},#{username},#{birthday},#{sex},#{address})
注意这里使用的order是“BEFORE”
首先自定义一个序列且用于生成主键,selectKey使用如下:
keyProperty="id">
SELECT 自定义序列.NEXTVAL FROM DUAL
insert into user(id,username,birthday,sex,address)
values(#{id},#{username},#{birthday},#{sex},#{address})
注意这里使用的order是“BEFORE”
简单例子
第一步,创建po类User
package com.caokaiyuan.po;
import java.util.Date;
public class User
{
private int id;
private String username;// 用户姓名
private String sex;// 性别
private Date birthday;// 生日
private String address;// 地址
set和get方法省略。。
第二步,配置UserMapper.xml文件
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
SELECT LAST_INSERT_ID()
insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})
第三步,编写UserMapper.java接口
//插入数据
public void insertUser(User user) throws Exception;
测试
package com.caokaiyuan.test;
import java.io.IOException;
import java.util.Date;
import java.util.List;
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.Before;
import org.junit.Test;
import com.caokaiyuan.mapper.UserMapper;
import com.caokaiyuan.po.User;
public class UserTest
{
private SqlSessionFactory sqlSessionFactory;
@Before
public void before()
{
try {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("SqlMapConfig.xml"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void testinsertUser() throws Exception
{
SqlSession session = sqlSessionFactory.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
User user = new User();
user.setAddress("桂平");
user.setSex("2");
user.setBirthday(new Date());
user.setUsername("张三");
userMapper.insertUser(user);
session.commit();
session.close();
System.out.println(user.getId());
}
}