```java
@SpringBootTest
public class StudentRepositoryTest {
@Autowired
private StudentRepository studentRepository;
/**
* select * from student where name like '张%' and sex='男'
*/
@Test
public void example1() {
//构建查询条件
Specification<Student> stuSpec = (root, query, cb) -> {
Predicate likeName = cb.like(root.get("name").as(String.class), "张%");
Predicate sexEqual = cb.equal(root.get("sex").as(String.class), "男");
Predicate and = cb.and(likeName, sexEqual);
return and;
};
List<Student> studentList = studentRepository.findAll(stuSpec);
//如果没有数据,则返回空的List,不会返回null
System.out.println(studentList);
//[Student(id=1, name=张三, age=25, sex=男, total=175), ...]
}
/**
* select distinct * from student where sex='男'
*/
@Test
public void example2() {
Specification<Student> stuSpec = (root, query, cb) -> {
CriteriaQuery cq = query.distinct(true);
Predicate sex = cb.equal(root.get("sex").as(String.class), "男");
return cq.where(sex).getRestriction();
};
List<Student> studentList = studentRepository.findAll(stuSpec);
System.out.println(studentList);
//[Student(id=1, name=张三, age=25, sex=男, total=175), ...
}
/**
* select * from student where id=? and name=? and (sex=? or total >= ?)
*/
@Test
public void example03() {
Student student = Student.builder().id(2).name("李四").age(24).sex("男").total(179).build();
Specification<Student> stuSpec = (root, query, cb) -> {
List<Predicate> predicates = new ArrayList<>(1);
if (student.getId() != null) {
Predicate predicate = cb.equal(root.get("id").as(Integer.class), student.getId());
predicates.add(predicate);
}
if (student.getAge() != null) {
Predicate predicate = cb.equal(root.get("age").as(Integer.class), student.getAge());
predicates.add(predicate);
}
List<Predicate> predicates02 = new ArrayList<>(1);
if (!StringUtils.isEmpty(student.getSex())) {
Predicate predicate = cb.equal(root.get("sex").as(String.class), student.getSex());
predicates02.add(predicate);
}
if (student.getTotal() != null) {
Predicate predicate = cb.greaterThanOrEqualTo(root.get("total").as(Integer.class), student.getTotal());
predicates02.add(predicate);
}
Predicate predicate = cb.or(predicates02.toArray(new Predicate[predicates02.size()]));
predicates.add(predicate);
return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
};
List<Student> studentList = studentRepository.findAll(stuSpec);
System.out.println(studentList);
//[Student(id=2, name=李四, age=24, sex=男, total=179)]
}
}
```
- MapStruct属性映射
- MapStruct是什么
- maven依赖
- 基本映射
- 字段名不一致的映射
- 字段类型不一致的映射
- 基本数据类型转换
- 日期格式转换
- 使用表达式转换
- 枚举映射
- 多个源类的映射
- 集合的映射
- 添加自定义映射方法
- 映射前后
- 添加默认值
- 映射异常处理
- SpringDataJPA
- SpringDataJPA是什么
- 与JPA、Hibernate的关系
- 环境搭建
- 简单CURD操作
- 内部原理
- 主键生成策略
- 联合主键
- 查询方式
- 方法命名规则查询
- 限制查询结果查询
- 注解@Query查询
- 命名参数查询
- SpEL表达式查询
- 原生查询
- 更新与删除
- Specification动态查询
- 核心接口
- 查询例子
- 分页查询与排序
- 多表查询
- 一对一查询
- 一对多查询
- 多对多查询
- 注意事项
- Specification多表查询
- @Query多表查询
- 只查询指定字段
- 级联操作
- 加载规则