批量添加
xxMapper.xml里面的代码
<!--
批量添加
insert into employee (name,age,sex) values
("小小良",45,false),("大二良",45,true)
foreach:循环
collection:遍历的集合
item:每次遍历拿到的对象
separator:分隔符(每个值都使用,隔开)
-->
<insert id="batchSave" parameterType="list">
insert into employee (name,age,sex) values
<foreach collection="list" item="e" separator=",">
(#{e.name},#{e.age},#{e.sex})
</foreach>
</insert>
测试方法
@Test
public void testBatchSave() throws Exception{
//准备数据
List<Employee> list = new ArrayList<>();
for (int i = 0; i < 20; i++) {
Employee employee = new Employee();
employee.setName("小王"+i);
employee.setAge(14+i);
employee.setSex(true);
list.add(employee);
}
SqlSession session = MyBatisUtil.openSession();
session.insert("cn.itsource.dao.EmployeeMapper.batchSave",list);
session.commit();
}
批量删除
xxMapper.xml里的代码
<!--
批量删除:DELETE FROM employee WHERE id in (?,?,?,...)
传 : List<Long> ids
foreach:循环
collection:遍历的集合
item:每次遍历拿到的对象
separator:分隔符(每个值都使用,隔开)
open:以什么开头
close:以什么结尾
index:遍历的索引
-->
<delete id="batchDelete" parameterType="list">
delete from employee where id in
<foreach collection="list" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
测试代码
@Test
public void testBatchDelete() throws Exception{
//准备数据
List<Long> ids = Arrays.asList(12L,14L);
SqlSession session = MyBatisUtil.openSession();
session.delete("cn.itsource.dao.EmployeeMapper.batchDelete",ids);
session.commit();
}
动态修改
xxxMapper.xml代码
<!--
动态修改:只修改有值的数据
-->
<update id="dynamicUpdate" parameterType="employee">
update employee
<set>
<if test="name!=null">
name=#{name},
</if>
<if test="age!=null">
age=#{age},
</if>
<if test="sex!=null">
sex=#{sex},
</if>
</set>
where id=#{id}
</update>
测试代码
@Test
public void testDynamicUpdate() throws Exception{
//准备数据
Employee employee = new Employee();
employee.setId(3L);
employee.setName("良阿");
// employee.setSex(true);
employee.setAge(22);
SqlSession session = MyBatisUtil.openSession();
session.update("cn.itsource.dao.EmployeeMapper.dynamicUpdate",employee);
session.commit();
}