insert 标签是用于定义插入语句的.
insert 有几个常用的属性:
<insert
id="insertAuthor"
parameterType="domain.blog.Author"
flushCache="true"
statementType="PREPARED"
keyProperty=""
keyColumn=""
useGeneratedKeys=""
timeout="20">
insert>
Mapper中方法定义:
// 返回值为空
void insert(Employee emp);
// 返回值为布尔类型
boolean insert(Employee emp);
// 返回值为删除的条数
long insert(Employee emp);
sql 片段:
<insert id="save" useGeneratedKeys="true" keyProperty="id">
insert into t_employee values (null, #{name}, #{sex}, #{age}, #{entryDate})
insert>
<insert id="save" useGeneratedKeys="true" keyProperty="id">
insert into t_employee(id, name, sex, age, entryDate) values (null, #{name}, #{sex}, #{age}, #{entryDate})
insert>
<insert id="batchSave" useGeneratedKeys="true" keyProperty="id">
insert into t_employee(id, name, sex, age, entryDate)
values
<foreach collection="list" separator="," item="emp">
(null, #{emp.name}, #{emp.sex}, #{emp.age}, #{emp.entryDate})
foreach>
insert>
public interface EmployeeMapper {
// 保存
boolean save(EmployeePO employeePO);
// 批量保存
long batchSave(List<EmployeePO> employeePOList);
}
// 测试保存方法
@Test
public void save(){
EmployeeMapper employeeMapper = SqlSessionUtil.getMapper(EmployeeMapper.class, true);
for (int i = 1; i <= 10; i++) {
EmployeePO employeePO = new EmployeePO("lisa_" + i, 20, "W", LocalDate.of(2018, 05, i));
boolean flag = employeeMapper.save(employeePO);
// 校验是否保存成功
Assert.assertEquals(true, flag);
// 校验是否回填id
Assert.assertNotNull(employeePO.getId());
}
}
// 测试批量保存
@Test
public void batchSave(){
EmployeeMapper employeeMapper = SqlSessionUtil.getMapper(EmployeeMapper.class, true);
List<EmployeePO> empList = new ArrayList<>();
empList.add(new EmployeePO("lisi_01", 26, "M", LocalDate.now()));
empList.add(new EmployeePO("lisi_02", 26, "M", LocalDate.now()));
empList.add(new EmployeePO("lisi_03", 26, "M", LocalDate.now()));
long num = employeeMapper.batchSave(empList);
Assert.assertEquals(3L, num);
}