how to get MyBatis insert primary key value in PostgreSQL 13 using identify as sequece

268 Views Asked by At

I am now using PostgreSQL 13, after insert record using MyBatis, I need to get the primary key of insert record. In the old way, I am using serial and the config would like this:

 <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>

recently I switch the PostgreSQL primary key as an identify(I read the PostgreSQL manual and tell me this is a better way to generate serial primary key) like this:

ALTER TABLE rss_sub_source 
    ALTER id SET NOT NULL,  -- optional
    ALTER id ADD GENERATED ALWAYS AS IDENTITY 
        (START WITH 1233);

and the table does not contain sequence, what should I do to get the primary key now?

1

There are 1 best solutions below

0
On BEST ANSWER

The best way is to use the native JDBC support for generated keys. The JDBC driver will retrieve the new value. You can set this up in MyBatis Generator like this:

<table tableName="article">
  <generatedKey column="ID" sqlStatement="JDBC" />
</table>