注意:本教程使用的数据库脚本、数据模型和环境信息请参考 “MyBatis Plus环境准备” 章节,点击下载示例源码。
本章节将介绍 between 和 notBetween 条件,它们定义如下:
between(R column, Object val1, Object val2) between(boolean condition, R column, Object val1, Object val2)
上面的 between 对应 SQL 语句中的 between 关键字,实例:
QueryWrapper<UserBean> wrapper = new QueryWrapper<>(); wrapper.between("age", 18, 30); // 等价于 SQL 语句:age between 18 and 30
notBetween(R column, Object val1, Object val2) notBetween(boolean condition, R column, Object val1, Object val2)
上面的 between 对应 SQL 语句中的 not between 关键字,实例:
QueryWrapper<UserBean> wrapper = new QueryWrapper<>(); wrapper.notBetween("age", 18, 30); // 等价于 SQL 语句:age not between 18 and 30
参数说明:
column:要用于条件筛选的数据库表列名称,如:name
val1:用于指定数据表列的值,条件将根据该值进行筛选
val2:用于指定数据表列的值,条件将根据该值进行筛选
condition:用于指定当前这个条件是否有效;如果为 true,则应用当前条件;如果为 false,则忽略当前条件。
package com.hxstrive.mybatis_plus.simple_mapper.condition; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.hxstrive.mybatis_plus.mapper.SimpleMapper; import com.hxstrive.mybatis_plus.model.UserBean; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest class Condition6Test { @Autowired private SimpleMapper simpleMapper; @Test void contextLoads() { QueryWrapper<UserBean> wrapper = new QueryWrapper<>(); wrapper.between("user_id", 100, 105); List<UserBean> userBeanList = simpleMapper.selectList(wrapper); for(UserBean userBean : userBeanList) { System.out.println(userBean); } System.out.println("================== 分割线 ==================="); wrapper = new QueryWrapper<>(); wrapper.notBetween("age", 21, 90); userBeanList = simpleMapper.selectList(wrapper); for(UserBean userBean : userBeanList) { System.out.println(userBean); } } }
运行上面程序,将执行下面SQL语句:
Preparing: SELECT user_id,name,sex,age,face,salary,borthday FROM user WHERE (user_id BETWEEN ? AND ?) Parameters: 100(Integer), 105(Integer) Preparing: SELECT user_id,name,sex,age,face,salary,borthday FROM user WHERE (age NOT BETWEEN ? AND ?) Parameters: 21(Integer), 90(Integer)