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 @ 2022-03-29 23:28  酸菜鱼没有鱼  阅读(434)  评论(0)    收藏  举报