I have the following table and sequence
CREATE TABLE teacher
(
teacher_id serial NOT NULL,
teacher_name character varying(50),
CONSTRAINT teacher_pkey PRIMARY KEY (teacher_id)
)
CREATE SEQUENCE teacher_teacher_id_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 1
CACHE 1;
and want to get the primary key whenever I insert new record. When I run the following query, it works and return the primary key I want.
INSERT INTO teacher( teacher_name ) VALUES ('John') RETURNING teacher_id;
But when I use myBatis-Spring Mapper as follows
@Insert("INSERT INTO teacher( teacher_name ) " +
"VALUES ( #{teacherName} ) RETURNING teacher_id" )
public int insertTeacher(Teacher teacher);
and call the function with valid teacher
object, it inserted the value but returns -1.
And I also tried the followings
@Insert("INSERT INTO teacher( teacher_id, teacher_name ) " +
"VALUES ( #{teacherId}, #{teacherName} )" )
@SelectKey(statement="SELECT nextval('teacher_teacher_id_seq');", keyProperty="teacherId", before=true, resultType=int.class)
public int insertTeacher(Teacher teacher);
this return 1 no matter how many times I call
Can anyone tell me the reason why and give me the solution? Thanks in advance.
After doing a lot of search, unlike the solution given in this link which might work for older versions or iBatis(but this does not work with latest version), I found out that myBatis 3.x.x simply does not support returning auto generate id/key on insert. Instead it returns the number row updated, so in my case it returns 1. You can read more on this link.