Mybatis 插入一条或批量插入 返回带有自增长主键记录的实例 Mybatis 是一个基于 Java 的持久层框架,它提供了对数据库的访问和操作的功能。今天,我们将分享一个关于 Mybatis 插入一条或批量插入 返回带有自增长主键记录的实例。 Mybatis 插入一条或批量插入 在 Mybatis 中,要实现插入一条或批量插入,需要使用 `<insert>` element,并在其中使用 `useGeneratedKeys` 和 `keyProperty` 属性来获取自增长主键。 MySQL 在 MySQL 中,需要使用 `useGeneratedKeys="true"` 和 `keyProperty="id"` 来获取自增长主键。例如: ```xml <insert id="insertByBatch" useGeneratedKeys="true" keyProperty="id" parameterType="java.util.List"> insert into test (sblsh, xh, jsjg, is_success, is_display, gmt_create, gmt_modify, create_user) values <foreach collection="list" item="item" index="index" separator=","> ( #{item.sblsh,jdbcType=BIGINT}, #{item.xh,jdbcType=CHAR}, #{item.jsjg,jdbcType=BIGINT}, #{item.isSuccess,jdbcType=TINYINT}, #{item.isDisplay,jdbcType=TINYINT}, SYSDATE(), SYSDATE(), #{item.createUser,jdbcType=VARCHAR} ) </foreach> </insert> ``` Oracle 在 Oracle 中,需要使用 `selectKey` element 来获取自增长主键。例如: ```xml <insert id="insertBatch"> <selectKey keyProperty="id" resultType="Long" order="BEFORE"> select test.nextval as id from dual </selectKey> insert into test (id,value,gmt_create,gmt_modified) select test.nextval, A.* FROM ( <foreach collection="list" item="item" index="index" separator="union all"> select #{item.value,jdbcType=VARCHAR}, #{item.gmtCreate,jdbcType=DATE}, #{item.gmtModified,jdbcType=DATE} from dual </foreach> ) A </insert> ``` 版本要求 需要注意的是,在 Mybatis 3.3.0 及其之前的版本中,不支持批量插入返回带主键的功能。需要升级到 Mybatis 3.3.1 及其以上版本。 总结 通过上面的示例,我们可以看到 Mybatis 插入一条或批量插入 返回带有自增长主键记录的实例的实现方式。在 MySQL 中,我们使用 `useGeneratedKeys` 和 `keyProperty` 属性,而在 Oracle 中,我们使用 `selectKey` element 来获取自增长主键。

























- 粉丝: 1
我的内容管理 展开
我的资源 快来上传第一个资源
我的收益
登录查看自己的收益我的积分 登录查看自己的积分
我的C币 登录后查看C币余额
我的收藏
我的下载
下载帮助


最新资源



- 1
- 2
前往页