简体   繁体   中英

MyBatis 3 + PostgreSQL - get primary key value on insertion

I have a Maven project that uses Java Spring, MyBatis, and MyBatis-Spring to map objects to a PostgreSQL database. I want to be able to query the value of the primary key at the same time that I insert a new record, and have yet to find a method that works. My current implementation does not return the correct value; it appears to always be returning 1.

This is the mapper's XML configuration for the query:

<insert id="registerNewUser" parameterType="com.hunter.databasejar.User">
    <selectKey keyProperty="ID" resultType="int">
      SELECT currval('"Users_ID_seq"')
    </selectKey>    
    insert into "Users" ("Username", "FirstName", "LastName") values (#{username}, #{firstName}, #{lastName})
</insert>

In Java, I write the following, and the value of i is always 1.

int i = sqlSession.insert("UserMapper.registerNewUser", user);

I have also tried altering the XML config to try the "returning" syntax from SQL, but always got an i value of -1.

<insert id="registerNewUser" parameterType="com.hunter.databasejar.User">
    insert into "Users" ("Username", "FirstName", "LastName") values (#{username}, #{firstName}, #{lastName}) returning "ID"
</insert>

My project is using MyBatis 3.2.4.

I think you need to change the case of the keyProperty to be id with a suitable setter

setId(int value);

AFAIK, there is no way to create a Javabeans-compatible setter for an upper-case field.

But the return value you are seeing is the number of rows inserted, not the allocated primary key value. There does not appear to be a way for MyBatis to harness the useful (but non-standard) returning clause.

To get the key value, you need to use the order= option in the selectKey declaration. This question has a couple of options for PostgreSQL Returning values from MyBatis <insert> mapped methods The technique described will update the id field in the object supplied to the method.

I use an Oracle database, so don't feel qualified to recommend an answer for PostgreSQL. But as a side note, if the order="BEFORE" option works with PostgreSQL, it is compatable with Oracle.

I found that my issue was that I had two columns with "id" somewhere in them. MyBatis was trying to map my column named "CognitoID" to my plain old "ID" column and blowing up when the cognito ID wasn't something that could be converted to an int.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM