Dolphin
Dolphin

Reputation: 38731

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

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?

Upvotes: 0

Views: 299

Answers (1)

Jeff Butler
Jeff Butler

Reputation: 991

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>

Upvotes: 1

Related Questions