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.