11.2 基于注解的动态SQL4 delete
Provider类中定义生成delete语句的方法
/MyADynamicSQLTest/src/mapper/EmployeeDynamicSQLProvider.java1 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接口中使用@DeleteProvider引用动态delete语句方法
/MyADynamicSQLTest/src/mapper/EmployeeMapper.java1 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 { sqlSession = SqlSessionFactoryTools.getSqlSession(); EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class); Employee delCondition = new Employee(); delCondition.setId(1); delCondition.setSex("女"); 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