MyBatis中单个插入与批量插入

使用mybatis ORM框架进行数据的插入操作

先假设数据库中有一个user表,其具体信息如下:
image

1.使用MySQL作为连接数据库时

一条数据插入时的方式
点击查看代码
<!-- 方式一 -->
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
insert into user_demo(id,user_name,password,email,age,sex)
values(#{id},#{userName},#{password},#{email},#{age},#{sex})
</insert>
<!-- 方式二:选择插入 -->
<sql id="insert_prefix">
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="userName != null and userName !=''">
user_name,
</if>
<if test="password != null and password !=''">
password,
</if>
<if test="email != null and email !=''">
email,
</if>
<if test="age != null">
age,
</if>
<if test="sex != null and sex !=''">
sex,
</if>
<if test="deptId != null">
dept_id,
</if>
</trim>
</sql>
<sql id="insert_suffix">
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id},
</if>
<if test="userName != null and userName !=''">
#{userName},
</if>
<if test="password != null and password !=''">
#{password},
</if>
<if test="email != null and email !=''">
#{email},
</if>
<if test="age != null">
#{age},
</if>
<if test="sex != null and sex !=''">
#{sex},
</if>
<if test="deptId != null">
#{deptId},
</if>
</trim>
</sql>
<insert id="insertUserSelect" useGeneratedKeys="true" keyProperty="id">
insert into user_demo
<include refid="insert_prefix"/>
values
<include refid="insert_suffix"/>
</insert>
批量插入数据
点击查看代码
<insert id="insertBatchUser" useGeneratedKeys="true" keyProperty="id">
insert into user_demo(id,user_name,password,email,age,sex)
values
<foreach collection="list" item="item" open="(" separator="," close=")">
#{item.id},#{item.userName},#{item.password},#{item.email},#{item.age},#{item.sex}
</foreach>
</insert>
posted @   酸菜鱼没有鱼  阅读(422)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示