0%

11.2 基于注解的动态SQL4 delete

11.2 基于注解的动态SQL4 delete

生成动态SQL的方法

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接口方法

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
package test;
import org.apache.ibatis.session.SqlSession;
import domain.Employee;
import fractory.SqlSessionFratoryTools;
import mapper.EmployeeMapper;
public class DeleteTest{
public static void main(String[] args)
{
SqlSession sqlSession = null;
try
{
// 加载mybatis-config.xml,获取SqlSession实例
sqlSession = SqlSessionFratoryTools.getSqlSession();
// 获取mapper接口代理对象
EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
Employee employee = new Employee();
employee.setId(1);
// employee.setLoginname();
// employee.setPassword();
// employee.setName();
employee.setSex("女");
// employee.setAge(18);
// employee.setPhone();
// employee.setSal();
// employee.setState();
employeeMapper.deleteEmployeeByPO(employee);
// 提交事务
sqlSession.commit();
} catch (Exception e)
{
// 出错回滚事务
sqlSession.rollback();
e.printStackTrace();
} finally
{
// 关闭会话
if(sqlSession != null)
sqlSession.close();
}
}
}

运行结果

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

原文链接: 11.2 基于注解的动态SQL4 delete