In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
本篇内容主要讲解"mybatis怎么实现批量插入并返回主键",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"mybatis怎么实现批量插入并返回主键"吧!
mybatis批量插入并返回主键(xml和注解两种方法)mybatis批量插入
在mysql数据库中支持批量插入,所以只要配置useGeneratedKeys和keyProperty就可以批量插入并返回主键了。
比如有个表camera,里面有cameraNo,chanIndex,cameraName这三个字段,其中cameraNo是自增主键。
下面是批量插入的Dao层接口:
void batchInsertCameras(@Param("list") List cameras);xml形式 insert into camera (chanIndex,cameraName) values (#{c.chanIndex},#{c.cameraName}) 注解形式@Insert("insert into camera (chanIndex,cameraName) values " + "(#{c.chanIndex},#{c.cameraName})")@Options(useGeneratedKeys = true, keyProperty = "cameraNo")void batchInsertCameras(@Param("list") List cameras);
注意:@Param里必须写成list, foreach的collection也必须写成list,否则批量插入后会报错说找不到"cameraNo"字段,而无法返回主键。
通过上面的xml形式或者注解形式的配置(我这是spring boot的项目,引入的mybatis-spring-boot-starter,采用的是注解形式),就可以批量插入并返回主键了,主键会被设置到Camera对象的cameraNo字段中。
cameraMapper.batchInsertCameras(cameras);for(Camera camera : cameras){ System.out.println(camera.getCameraNo());}
执行批量插入时,需确保至少有一条待插入的记录,否则会导致sql有误而报错。
mybatis批量插入并返回主键笔记mapper中的代码int insertBatchUserReturnId(List users);
也可以在形参前面加上@Param("xxxx")
xml中的代码,collection必须填list类型 insert into message (user_id, user_name, user_type, user_passwd, user_phone,user_pic,user_address) values #{item.userId,jdbcType=INTEGER}, #{item.userName,jdbcType=VARCHAR}, #{item.userType,jdbcType=TINYINT}, #{item.userPasswd,jdbcType=VARCHAR}, #{item.userPhone,jdbcType=VARCHAR}, #{item.userPic,jdbcType=VARCHAR},#{item.userAddress,jdbcType=VARCHAR} 到此,相信大家对"mybatis怎么实现批量插入并返回主键"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.