Mybatis在oracle数据库中插入数据后返回自增ID值

时间:2022-08-27 21:47:31

Mybatis 示例之 SelectKey:http://blog.csdn.net/isea533/article/details/21153791


1. Oracle数据库中创建自增序列

create sequence SEQ_USER_ID
start with 1
increment by 1
minvalue 1
nomaxvalue
nocycle

2. mybatis的mapper.xml中:

(selectKey的结果会放进传参user对象中)

  <insert id="createUser" parameterType="pojo.User">
<selectKey keyProperty="userId" resultType="int" order="BEFORE">
select SEQ_USER_ID.NEXTVAL from dual
</selectKey>
insert into "USER" (USER_ID, USER_NAME, PASSWORD)
values (#{userId,jdbcType=DECIMAL}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}
)
</insert>


3. 

User user = new User();
user.setUserName("abc");
user.setPassword("abc");
System.out.println(userService.createUser(user));
System.out.println(user.getUserId());
插入成功则输出1和userId值。