Mybatis插入数据后返回自增主键
在Oracle环境中返回自增主键
Oracle中自增主键的实现条件一般是使用序列
--创建一个测试表
create table test_user(
id number(32) primary key,
name varchar2(32)
);
--创建注释
comment on table test_user is '测试用户表';
comment on column test_user.id is '测试用户主键';
comment on column test_user.name is '测试用户姓名';
--创建序列
create sequence seq_test_user
start with 1
increment by 1
maxvalue 99999999999999999999
cache 20
order
cycle
--新增一条数据,使用ID自增
insert into table test_user values(seq_test_user.nextval, '大土');
Mybatis XML配置
<insert id="insert" parameterType="cn.khue.test.TestUser">
<selectKey keyProperty="id" resultType="java.math.BigDecimal" order="BEFORE">
select seq_test_user.nextval from dual
</selectKey>
insert into test_test (id, name)
values(#{id, jdbcType=DECIMAL}, #{name, jdbcType=VARCHAR})
</insert>
Java代码
public class TestUserServiceImpl implements TestUserService{
@Autowird
private TestUserMapper testUserMapper;
@Override
public Result addTestUser(TestUser testUser){
//插入数据
testUserMapper.insert(testUser);
//获取ID
BigDecimal id = testUser.getId();
}
}
在MySQL环境中返回自增主键
在Mybatis XML配置文件中开启useGeneratedKeys和keyProperty属性
<insert id="insert" parameterType="cn.khue.test.TestUser" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
insert into test_test (name)
values(#{name, jdbcType=VARCHAR})
</insert>