MyBatis 是支持普通 SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML或注解用于配置和原始映射,将接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。在使用MyBatis做持久层操作时,insert语句默认是不返回记录主键ID值的,而是返回插入的记录条数;如果业务要求需要返回主键ID值时,可以通过如下配置方式来实现此功能。
下面介绍Oracle与mysql两种数据库,分别获取主键ID值得配置:
1)针对Oracle数据库,Sequence主键而言具体配置代码如下:
<insert id="addProfile" parameterType="www.yoodb.com.entity.Profile"> <selectKey resultType="java.lang.Short" order="BEFORE" keyProperty="id"> SELECT SEQ_YOODB.NEXTVAL FROM DUAL </selectKey> insert into profile (name,address,ip,mobile,createTime) values (#{name},#{address},#{ip},#{mobile},#{createTime}) </insert>
2)针对Mysql数据库,具体配置代码如下:
<insert id="addProfile" parameterType="www.yoodb.com.entity.Profile" useGeneratedKeys="true" keyProperty="id"> <selectKey keyProperty="id" resultType="java.lang.Short"> SELECT LAST_INSERT_ID() AS id </selectKey> insert into profile (name,address,ip,mobile,createTime) values (#{name},#{address},#{ip},#{mobile},#{createTime}) </insert>
或:
<insert id="addProfile" parameterType="www.yoodb.com.entity.Profile"> <selectKey resultType="java.lang.Short" order="AFTER" keyProperty="id"> SELECT LAST_INSERT_ID() AS id </selectKey> insert into profile (name,address,ip,mobile,createTime) values (#{name},#{address},#{ip},#{mobile},#{createTime}) </insert>
注意:selectKey中order属性的值是不同的,BEFORE先选择主键,设置keyProperty的值然后执行插入语句;而AFTER是先执行插入语句,然后执行selectKey。