1.mysql
useGeneratedKeys --true主键自增
<insert id="save"
parameterType="com.xxx.User"
useGeneratedKeys="true"keyProperty="id">
insert into table_name(username,password) values (
#{username,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR}
)
</insert>
2.oracle
1)数据库中创建了序列,触发器情况下
order类型AFTER--代表在insert语句执行后 BEFORE --代表在insert语句执行后
keyProperty --返回属性
t_user_id_SEQ --序列
查询全部序列,找到你自己的表的序列
SELECT * FROM user_sequences
<insert id="save" parameterType="com.xxx.User">
<selectKey resultType="Long" order="AFTER" keyProperty="id">
select t_user_id_SEQ.CURRVAL as id from dual
</selectKey>
insert into table_name(username,password) values (#{username,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR}
)
2)数据库创建序列,未创建触发器
<insert id="save" parameterType="com.xxx.User">
<selectKey resultType="Long" order="BEFORE" keyProperty="id">
select t_user_id_SEQ.NEXTVAL as id from dual
</selectKey>
insert into table_name(username,password) values (#{username,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR}
)
在实体类中使用
User user = new User();
user.setUsername(username);
user.setPassword(password);
userDao.save(user);
return user.getId();