Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get auto-genearated key for the inserted record in mybatis

I am working under a web application which use spring mvc + mybatis + mysql.

And I found that I can not get the auto-generated key for the last inserted record (I have googled so much).

This is the related configuration(take the model 'Post' for example):

spring.xml:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    //omitted
</bean>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation" value="config.xml" />
</bean>

<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg index="0" ref="sqlSessionFactory" />
</bean>

mybatis config.xml

<configuration>
    <typeAliases>
        <typeAlias alias="Post" type="com.king.model.Post" />
    </typeAliases>
    <mappers>
        <mapper resource="com/king/model/PostMapper.xml" />
    </mappers>
</configuration>

PostMapper.xml:

<mapper namespace="com.king.model.PostMapper">
    <insert id="insert" parameterType="Post">
        insert into posts (title,body,created_at,updated_at) values (#{title},#{body},#{createDate},#{updateDate})
    </insert>
</mapper>

Dao:

public abstract class AbstractSimpleDaoImpl<T> extends SqlSessionDaoSupport{
    @Override
    public int add(T entity) {
        return getSqlSession().insert(getMapperNamespace() + ".insert", entity);
    }

    protected abstract String getMapperNamespace();
}

public class PostDao extends AbstractSimpleDaoImpl<Post> {
    @Override
    protected String getMapperNamespace() {
        return "com.king.model.PostMapper";
    }
}

However,when I insert a new Post to database:

postDao.add(post);

I can not get the generated id for the inserted post. I always get 1. I know this is the row-affected number.

Also,I read the mybatis guide,and I tried this:

<insert id="insert" parameterType="Post" useGeneratedKeys="true" keyProperty="id">

But it seems that,this does not work.

How to fix it?

like image 947
hguser Avatar asked Nov 28 '22 02:11

hguser


2 Answers

In fact the following works:

<insert id="insert" parameterType="Post" useGeneratedKeys="true" keyProperty="id">

postDao.add(post);

will return 1 as before,but post.getId() will get the key.

like image 93
hguser Avatar answered Dec 05 '22 11:12

hguser


This can be done using annotations as well.

final String INSERT = "insert into posts (title,body,created_at,updated_at) values (#{title},#{body},#{createDate},#{updateDate})";

@Insert(INSERT)
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
void insert(Post post) throws Exception;

Set keyProperty as the Java variable name.

Set keyColumn as the column name in the database.

After insert, post.getId() will have your generated ID.

like image 42
user2601995 Avatar answered Dec 05 '22 11:12

user2601995