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(){ { 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 { sqlSession = SqlSessionFratoryTools.getSqlSession(); EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class); Employee employee = new Employee(); employee.setId(1); employee.setSex("女"); 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