首先在postgresql插入主键自动生成序列:
CREATE SEQUENCE test_c_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
alter table test_c alter column id set default nextval('test_c_id_seq');
然后mapper.xml配置:
<!-- 新建一个用户 -->
<insert id="insertUser" parameterType="com.nari.entity.RsUser">
<selectKey order="AFTER" keyProperty="userid" resultType="int">
SELECT currval('nari.test_c_id_seq3')
</selectKey>
insert into nari.rs_user (username,password) values(#{username},#{password})
</insert>
order为after表示插入完成后获取主键,主键字段为userid,然后
RsUser user = new RsUser();
user.getUserid()即可获取当前插入记录的主键。