Oracle使用MyBatis插入一条数据自动递增主键并返回主键值

时间:2020-12-10 00:41:59

前期准备

--创建t_table表
create table t_user(
id   number(10)   primary key,
name varchar2(20),
age  number(3)
);
comment on table  t_user      is '用户信息表';
comment on column t_user.id   is '主键';
comment on column t_user.name is '用户名';
comment on column t_user.age  is '用户年龄';


--创建序列
create sequence seq_user_id
start with 1
increment by 1;

MyBatis配置

略.

XML编写插入语句

    <insert >
        <selectKey resultType="java.lang.Integer" order="BEFORE" keyProperty="id">
            SELECT seq_user_id.nextval  FROM DUAL
        </selectKey>
        insert into t_user(id,name, age)
        values (#{id},#{name}, #{age})
    </insert>

测试

    @Test
    public void test01() {
        UserMapper mapper = SqlSessionUtil.getSqlSession().getMapper(UserMapper.class);
        User tom = new User(null, "tom", 19);
        mapper.insertUser(tom);
        System.out.println("tom = " + tom);
    }

测试结果 Oracle使用MyBatis插入一条数据自动递增主键并返回主键值