11.2.1 基于注解的动态SQL4 delete

11.2 基于注解的动态SQL4 delete

Provider类中定义生成delete语句的方法

/MyADynamicSQLTest/src/mapper/EmployeeDynamicSQLProvider.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public String deleteEmployeeByPO(Employee parm)
{
return new SQL(){
{
// 在这里写上动态SQL的生成逻辑...
DELETE_FROM("tb_employee");
if (parm.getId() != null)
{
WHERE("id=#{id}");
}
if (parm.getLoginname() != null)
{
WHERE("loginname=#{loginname}");
}
if (parm.getPassword() != null)
{
WHERE("password=#{password}");
}
if (parm.getName() != null)
{
WHERE("name=#{name}");
}
if (parm.getSex() != null)
{
WHERE("sex=#{sex}");
}
if (parm.getAge() != null)
{
WHERE("age=#{age}");
}
if (parm.getPhone() != null)
{
WHERE("phone=#{phone}");
}
if (parm.getSal() != null)
{
WHERE("sal=#{sal}");
}
if (parm.getState() != null)
{
WHERE("state=#{state}");
}
}
}.toString();
}

mapper接口中使用@DeleteProvider引用动态delete语句方法

/MyADynamicSQLTest/src/mapper/EmployeeMapper.java
1
2
3
4
5
@DeleteProvider(
type = EmployeeDynamicSQLProvider.class,
method = "deleteEmployeeByPO"
)
void deleteEmployeeByPO(Employee employee);

测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package test;

import org.apache.ibatis.session.SqlSession;
import domain.Employee;
import fractory.SqlSessionFactoryTools;
import mapper.EmployeeMapper;

public class DeleteTest {
public static void main(String[] args) {
SqlSession sqlSession = null;
try {
// 加载mybatis-config.xml,获取SqlSession实例
sqlSession = SqlSessionFactoryTools.getSqlSession();
// 获取mapper接口代理对象
EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
// 创建一个新的对象保存要删除的条件
Employee delCondition = new Employee();
// 添加条件
delCondition.setId(1);
// employee.setLoginname();
// employee.setPassword();
// employee.setName();
delCondition.setSex("女");
// employee.setAge(18);
// employee.setPhone();
// employee.setSal();
// employee.setState();
employeeMapper.deleteEmployeeByPO(delCondition);
// 提交事务
sqlSession.commit();
} catch (Exception e) {
// 出错回滚事务
sqlSession.rollback();
e.printStackTrace();
} finally {
// 关闭会话
if (sqlSession != null)
sqlSession.close();
}

}
}

运行结果

DEBUG [main] ==>  Preparing: DELETE FROM tb_employee WHERE (id=? AND sex=?) 
DEBUG [main] ==> Parameters: 1(Integer), 女(String)
DEBUG [main] <==    Updates: 0