一、EntityWrapper介紹
在實際的開發過程中更多的是帶有復雜條件的SQL操作,而不是簡單的增刪改查。而在這方面MP也提供了條件構造器EntityWrapper(簡稱EW)來讓開發者自由構建SQL操作條件。
注意:條件封裝屬性,使用的是數據庫字段,而不是Java實體屬性!
以下列出的是MybatisPlus提供的條件參數:
二、以下是EntityWrapper的使用例子
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations= {"classpath:applicationContext.xml"}) public class TestEntityWrapper { @Autowired private EmployeeMapper employeeMapper; @Test public void testEntityWrapperSelectPage() { //需要分頁查詢 tbl_employee 表中,年齡在 18~50 之間性別為男且姓名為 xx 的所有用戶 List<Employee> emps = employeeMapper.selectPage(new Page<Employee>(1, 2), new EntityWrapper<Employee>() .between("age", 18, 50) .eq("gender", 0) .eq("last_name", "jack")); System.out.println(emps); } @Test public void testEntityWrapperSelectList() { //需要查詢 tbl_employee 表中, 性別為男且姓名中帶有“J”的 或者 郵箱中帶有“a”的所有用戶 List<Employee> emps = employeeMapper.selectList(new EntityWrapper<Employee>() .eq("gender", 1) .like("last_name", "j") //.or() //WHERE (gender = ? AND last_name LIKE ? OR email LIKE ?) .orNew() //WHERE (gender = ? AND last_name LIKE ?) OR (email LIKE ?) .like("email", "a")); System.out.println(emps); } /** * 條件構造器 修改操作 */ @Test public void testEntityWrapperUpdate() { //修改tbl_employee 表中, 年齡為25且姓名為“jack”的用戶 //將修改的結果封裝成對象 Employee entity = new Employee(); entity.setLastName("Lucy"); entity.setEmail("lucy@121.com"); Integer res = employeeMapper.update(entity, //UPDATE tbl_employjee SET last_name=?, email=? WHERE (age = ? AND last_name = ?) new EntityWrapper<Employee>() .eq("age", 25) .eq("last_name", "jack") ); System.out.println("res: " + res); } /** * 條件構造器 刪除操作 */ @Test public void testEntityWrapperDelete() { //刪除名字有“o”且性別為女的用戶 employeeMapper.delete(new EntityWrapper<Employee>() //WHERE (last_name LIKE ? AND gender = ?) .like("last_name", "o") .eq("gender", 0) ); } /** * 條件構造器,排序操作 */ @Test public void testEntityWrapperSort() { //查詢為女的,根據age進行排序(asc/desc),簡單排序 List<Employee> page = employeeMapper.selectPage(new Page<Employee>(1, 2), new EntityWrapper<Employee>() // WHERE (gender = ?) ORDER BY age ASC .eq("gender", 0) //.orderAsc(Arrays.asList(new String[] {"age"}))); .orderBy("age") // WHERE (gender = ?) ORDER BY age Desc .last("Desc") //手動拼接SQL,有注入危險 ); System.out.println(page); } /** * Condiction的使用 */ @Test public void testConditionSelectPage() { //需要分頁查詢 tbl_employee 表中,年齡在 18~50 之間性別為男且姓名為 xx 的所有用戶 List<Employee> page = employeeMapper.selectPage(new Page<Employee>(1, 2), Condition.create() .between("age", 18, 50) .eq("gender", 1) .eq("last_name", "jack") ); System.out.println(page); } }