Constructing Database Queries with MyBatis-Plus Wrappers
MyBatis-Plus includes a robust set of Wrapper classes for creating complex database query conditions. The primary Wrapper types are:
- QueryWrapper: Builds query conditions with support for equality, inequality, greater-than, less-than, and other oeprations. It allows chaining multiple conditions and combining them with
andandorlogic. - UpdateWrapper: Constructs conditions for update operations, specifying which records to modify.
- LambdaQueryWrapper: A query wrapper that uses lambda expressions to reference entity class properties, eliminating hard-coded column names and improving code readability.
- LambdaUpdateWrapper: An update wrapper that similarly employs lambda expressions for specifying fields and conditions.
Common conditional methods include:
-
eq (equals)
QueryWrapper<Employee> wrapper = new QueryWrapper<>(); wrapper.eq("department", "Engineering"); // Or using lambda LambdaQueryWrapper<Employee> lambdaWrapper = new LambdaQueryWrapper<>(); lambdaWrapper.eq(Employee::getDepartment, "Engineering");Generated SQL:
SELECT * FROM employee WHERE department = 'Engineering' -
ne (not equals)
wrapper.ne("status", "inactive"); lambdaWrapper.ne(Employee::getStatus, "inactive");Generated SQL:
SELECT * FROM employee WHERE status <> 'inactive' -
gt (greater than)
wrapper.gt("salary", 50000); lambdaWrapper.gt(Employee::getSalary, 50000);Generated SQL:
SELECT * FROM employee WHERE salary > 50000 -
ge (greater than or equal to)
wrapper.ge("years_of_service", 5); lambdaWrapper.ge(Employee::getYearsOfService, 5);Generated SQL:
SELECT * FROM employee WHERE years_of_service >= 5 -
lt (less than)
wrapper.lt("remaining_vacation", 10); lambdaWrapper.lt(Employee::getRemainingVacation, 10);Generated SQL:
SELECT * FROM employee WHERE remaining_vacation < 10 -
le (less than or equal to)
wrapper.le("age", 65); lambdaWrapper.le(Employee::getAge, 65);Generated SQL:
SELECT * FROM employee WHERE age <= 65 -
between
wrapper.between("hire_date", "2023-01-01", "2023-12-31"); lambdaWrapper.between(Employee::getHireDate, "2023-01-01", "2023-12-31");Generated SQL:
SELECT * FROM employee WHERE hire_date BETWEEN '2023-01-01' AND '2023-12-31' -
notBetween
wrapper.notBetween("project_id", 100, 200); lambdaWrapper.notBetween(Employee::getProjectId, 100, 200);Generated SQL:
SELECT * FROM employee WHERE project_id NOT BETWEEN 100 AND 200 -
like
wrapper.like("last_name", "Smith"); lambdaWrapper.like(Employee::getLastName, "Smith");Generated SQL:
SELECT * FROM employee WHERE last_name LIKE '%Smith%'