I have a Java POJO:
public class Widget {
private int id;
private String name;
// ...
}
I am trying to use MyBatis to insert a new Widget into the widget table of my Postgres database, and for this insert method to inject the passed-in POJO with the auto-generated id of the newly-inserted widget table record:
// Notice the widget's id is left null.
Widget w = new Widget("name-of-widget");
WidgetMapperImpl widgetMapper = new WidgetMapperImpl();
widgetMapper.insertWidget(w);
// At runtime this prints null (the id is not being set).
System.out.println(w.getId());
And WidgetMapper.java:
public interface WidgetMapper {
public void insertWidget(@Param("widget") Widget widget);
}
Here is the WidgetMapper.xml:
<mapper namespace="com.myapp.WidgetMapper">
<cache flushInterval="360000" />
<resultMap id="WidgetMapperResult" type="com.myapp.Widget">
<result property="id" column="widget_id"/>
<result property="name" column="widget_name" />
</resultMap>
<insert id="insertWidget" parameterType="com.myapp.Widget" useGeneratedKeys="true" keyProperty="id">
INSERT INTO
myapp.widgets
(
widget_name
)
VALUES
(
#{widget.name}
);
<selectKey keyProperty="id" resultType="int" order="AFTER">
SELECT CURRVAL('widget_id_seq') AS widget_id
</selectKey>
</insert>
</mapper>
Again, this code compiles and builds fine. At runtime, after I call widgetMapper.insertWidget(Widget), and then try to access that’s Widget‘s id, it is null, so the ID-injection is not working. Can anyone spot why? Thanks in advance!
As far as I remember, you cannot use
useGeneratedKeys="true"andselectKeyat the same time.So a solution can be: either the implementation of the
getGeneratedKeysmethod of the JDBC driver for Postgres can deal with what you need (I don’t know how JDBC and postgres sequences works together), so you use onlyuseGeneratedKeys="true". Or you have to useselectKey, then you have to turn of theuseGeneratedKeysattribute.