Step1:
在pgSQL中创建序列
CREATE SEQUENCE "history_id_sequence"
INCREMENT 1
MINVALUE 1
MAXVALUE 9999999
START 1
CACHE 1;
在navicate中可以看到该序列的设置:(其他-序列)
在这里可以设置参数,来设置从哪一个数来开始自增

Step2:
将序列赋给主键hid
alter table user_table alter column uid set default nextval('user_id_sequence')
Step3:
在mapper中增加方法
public interface HistoryPOMapperExt {
int insertPrimaryKey(HistoryPO record);
}
Step4:
xml中实现方法:
<insert id="insertPrimaryKey" parameterType="com.xxx.springbootdemo.po.HistoryPO" >
<selectKey keyProperty="hid" resultType="Long" order="BEFORE">
select nextval('history_id_sequence'::regclass) as hid
</selectKey>
insert into history_table (hid, phone, card,
bookname, username, begintime,
endtime, status)
values (#{hid,jdbcType=BIGINT}, #{phone,jdbcType=VARCHAR}, #{card,jdbcType=VARCHAR},
#{bookname,jdbcType=VARCHAR}, #{username,jdbcType=VARCHAR}, #{begintime,jdbcType=VARCHAR},
#{endtime,jdbcType=VARCHAR}, #{status,jdbcType=SMALLINT})
</insert>
完成!
本文介绍了如何在pgSQL中创建序列,并将其应用到用户表的主键上实现自动增长。首先创建名为`history_id_sequence`的序列,然后修改表结构将序列赋给`user_table`的`uid`字段。接着在Mapper接口中添加插入方法,并在XML文件中配置SQL语句,使用`selectKey`标签获取序列的下一个值,确保主键`hid`的自动填充。

1237

被折叠的 条评论
为什么被折叠?



