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):
<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>
<configuration>
<typeAliases>
<typeAlias alias="Post" type="com.king.model.Post" />
</typeAliases>
<mappers>
<mapper resource="com/king/model/PostMapper.xml" />
</mappers>
</configuration>
<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>
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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With