简体   繁体   English

MyBatis获取最后插入ID

[英]MyBatis Get Last Insert Id

I have a Java POJO: 我有一个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: 我正在尝试使用MyBatis将新的Widget插入我的Postgres数据库的widget表中,并且对于此insert方法,使用新插入的widget表记录的自动生成的ID注入传入的POJO:

// 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 : WidgetMapper.java

public interface WidgetMapper {
    public void insertWidget(@Param("widget") Widget widget);
}

Here is the WidgetMapper.xml : 这是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. 在运行时,我调用widgetMapper.insertWidget(Widget)之后,尝试访问该Widget的ID,它为null,因此ID注入不起作用。 Can anyone spot why? 谁能找到原因? Thanks in advance! 提前致谢!

As far as I remember, you cannot use useGeneratedKeys="true" and selectKey at the same time. 据我所知,您不能同时使用useGeneratedKeys="true"selectKey

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" . 因此,解决方案可以是:用于Postgres的JDBC驱动程序的getGeneratedKeys方法的实现getGeneratedKeys您的需要(我不知道JDBC和postgres序列如何协同工作),因此仅使用useGeneratedKeys="true" Or you have to use selectKey , then you have to turn of the useGeneratedKeys attribute. 或者,您必须使用selectKey ,然后必须打开useGeneratedKeys属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM