我现在使用的是PostgreSQL 13,在使用MyBatis插入记录后,我需要获得插入记录的主键。按照旧的方式,我使用串行和配置如下:
<table tableName="article"
enableCountByExample="true"
enableUpdateByExample="true"
enableDeleteByExample="true"
enableSelectByExample="true"
selectByExampleQueryId="true">
<generatedKey column="ID" sqlStatement="SELECT currval('article_id_seq')" identity="true" />
</table>
最近,我将PostgreSQL主键作为标识进行了切换(我阅读了PostgreSQL手册,告诉我这是生成串行主键的更好方法(,如下所示:
ALTER TABLE rss_sub_source
ALTER id SET NOT NULL, -- optional
ALTER id ADD GENERATED ALWAYS AS IDENTITY
(START WITH 1233);
并且表中不包含序列,我现在应该怎么做才能获得主键?
最好的方法是对生成的密钥使用本机JDBC支持。JDBC驱动程序将检索新值。你可以在MyBatis Generator中这样设置:
<table tableName="article">
<generatedKey column="ID" sqlStatement="JDBC" />
</table>