```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多表查詢
- 只查詢指定字段
- 級聯操作
- 加載規則