一、QBC 查询
概念:Query By Criteria
Criteria 是 Criterion 的复数形式,意思是规则、标准、准则。在SQL语句中相当于查询条件。
QBC 查询是将查询条件通过java对象进行模块化封装。
二、案例
1、使用QBC 进行查询
/**
* SELECT distinct emp_name, emp_salary FROM tabple_emp
* WHERE ( emp_salary > ? and emp_age < ? )
* or ( emp_salary < ? and emp_age > ? )
* order by emp_salary ASC,emp_age DESC
*/
@Test
public void testSelectByExample() {
//目标:where (emp_salary>? and emp_age<?) or (emp_salary < ? and emp_age>?)
//1.创建 Example对象
Example example = new Example(Employee.class);
//**********************
//设置其他属性
//1.设置排序信息
example.orderBy("empSalary").asc().orderBy("empAge").desc();
//2.设置 "去重"
example.setDistinct(true);
//3.设置select字段
example.selectProperties("empName", "empSalary");
//**********************
//2. 通过 Example 对象创建 Criteria 对象
Example.Criteria criteria1 = example.createCriteria();
Example.Criteria criteria2 = example.createCriteria();
//3. 在两个Criteria对象中分别设置查询条件
//property:实体类的属性名 value:实体类的属性值
criteria1.andGreaterThan("empSalary", 100.00).andLessThan("empAge", 25);
criteria2.andLessThan("empSalary", 8000.00).andGreaterThan("empAge", 30);
//4. 使用OR组装两个Criteria对象
example.or(criteria2);
//5.执行查询
List<Employee> emp = employeeService.getEmpByExample(example);
emp.forEach(System.out::println);
}
public List<Employee> getEmpByExample(Example example) {
return employeeMapper.selectByExample(example);
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?