我们时长在批量插入时,需要获取插入数据的id.
这样:
<insert id="insertUser" parameterType="gys.entity.User" keyProperty="userId" useGeneratedKeys="true">INSERT INTO `user`
(userName)
VALUES
(#{userName})</insert>这样是没问题的.
但是有时候牵扯到批量插入,并且获取插入的id
这样写:
<insert id="insertUserBatch1" keyProperty="userId" useGeneratedKeys="true">INSERT INTO `user`
(userName)
VALUES<foreach collection="list" separator="," item="item">(#{item.userName})</foreach></insert>这样运行后就会出现异常了.
这是因为你用的mybatis版本过低.比如我用的是3.2.2版本,这是mybatis的一个bug.
如果你换成3.4.4版本就没有问题了.
上面的sql语句换个写法 就又会报异常了(将insert包围在foreach里面)
比如:
<insert id="insertUserBatch2"> <foreach collection="list" separator=";" item="item"> INSERT INTO `user`
(userName)
VALUES
(#{item.userName}) </foreach></insert>同理还有update的批量更新也是有这个问题
<update id="updateUserBatch"><foreach collection="list" item="item" separator=";">update `user` set
userName=#{item.userName}
where
userId=#{item.userId}</foreach></update>这是因为mybatis默认是只能执行一条sql语句,
可以再链接路径的时候加上参数,就可以执行多条sql语句了.allowMultiQueries=true
以上就是mybaits批量插入该如何操作的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号