原创

MyBatis 实现插入操作返回主键ID值

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。

~阅读全文-人机检测~

微信公众号“Java精选”(w_z90110),专注Java技术干货分享!让你从此路人变大神!回复关键词领取资料:如Mysql、Hadoop、Dubbo、Spring Boot等,免费领取视频教程、资料文档和项目源码。微信搜索小程序“Java精选面试题”,内涵3000+道Java面试题!

涵盖:互联网那些事、算法与数据结构、SpringMVC、Spring boot、Spring Cloud、ElasticSearch、Linux、Mysql、Oracle等

评论

分享:

支付宝

微信