简体   繁体   中英

MyBatis Get Last Insert Id

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" and selectKey at the same time.

So a solution can be: either the implementation of the getGeneratedKeys method 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 only useGeneratedKeys="true" . Or you have to use selectKey , then you have to turn of the useGeneratedKeys attribute.

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