Return 插入时主键不起作用 myBatis-Spring
Return primary key on insert does not work myBatis-Spring
我有以下table和序列
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;
并希望在我插入新记录时获取主键。当我 运行 以下查询时,它有效并且 return 我想要的主键。
INSERT INTO teacher( teacher_name ) VALUES ('John') RETURNING teacher_id;
但是当我使用myBatis-Spring Mapper时如下
@Insert("INSERT INTO teacher( teacher_name ) " +
"VALUES ( #{teacherName} ) RETURNING teacher_id" )
public int insertTeacher(Teacher teacher);
并使用有效的 teacher
对象调用函数,它插入了值但是 returns -1.
而且我还尝试了以下方法
@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);
这个return1不管我叫多少次
谁能告诉我原因并给我解决方案?
提前致谢。
找了很多,不像这个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中给出的解决方案。
我有以下table和序列
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;
并希望在我插入新记录时获取主键。当我 运行 以下查询时,它有效并且 return 我想要的主键。
INSERT INTO teacher( teacher_name ) VALUES ('John') RETURNING teacher_id;
但是当我使用myBatis-Spring Mapper时如下
@Insert("INSERT INTO teacher( teacher_name ) " +
"VALUES ( #{teacherName} ) RETURNING teacher_id" )
public int insertTeacher(Teacher teacher);
并使用有效的 teacher
对象调用函数,它插入了值但是 returns -1.
而且我还尝试了以下方法
@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);
这个return1不管我叫多少次
谁能告诉我原因并给我解决方案? 提前致谢。
找了很多,不像这个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中给出的解决方案。