java - 如何使用 JpaRepository,Spring-boot 在方法中查找没有参数的对象列表
问题描述
我需要使用 JpaRepository 获取对象列表,但在某些情况下,我没有方法中的变量之一。例如:
如果我需要 findByNombreCursoContainsIgnoreCaseAndAreaBean 但我没有变量Area,我应该怎么做?为我的每个查询案例创建具体方法?是否存在一种方法,我可以将空值传递给 Area 并获取所有区域的查询?
将会
findByNombreCursoContainsIgnoreCaseAndAreaBean("example", null);
并以此获取带有“示例”和所有区域的所有列表。
我想做什么?我的应用程序中的搜索者:我认为这不是最佳选择:
public Page<Curso> searcher(String nombreCurso, Area area, int activo, Pageable pageable){
try {
if(nombreCurso.isEmpty() && area!=null && area.getIdArea() == 0 && activo == 2) {
return getAll(pageable);
} if(area.getIdArea() == 0 && activo == 2) {
return repo.findByNombreCursoContainsIgnoreCase(nombreCurso, pageable);
} if(activo != 2 && area.getIdArea() == 0) { // 0 = descatalogado / 1 = Activo
return repo.findByNombreCursoContainsIgnoreCaseAndActivo(nombreCurso, new Integer(activo).byteValue(), pageable);
} if(activo != 2){
return repo.findByActivo(new Integer(activo).byteValue(), pageable);
}else {
return repo.findByNombreCursoContainsIgnoreCaseAndAreaBean(nombreCurso, area, pageable);
}
} catch(Exception ex) {
return getAll(pageable);
}
}
解决方案
您可以使用 org.springframework.data.domain.Example。以实体模型为例进行查询。由于只设置了 nombre 字段,因此仅考虑该字段来构建查询条件。如果您设置了除 null 以外的更多字段,这些字段也会添加到搜索条件中
Curso curso = new Curso();
curso.setNombre(5);
Page<Curso> page = cursoRepository.findAll(Example.of(curso),pageable);
推荐阅读
- matlab - 如何在矩阵中查找没有特定行的 NaN 元素的列的索引?
- python - 如何在熊猫中选择一个级别和所有子级别(和项目)?
- ios - 如何为 Data swift 添加扩展?
- java - 如何在边框底部的每个角落放置两个按钮
- xaml - 如何使用带有 Xamarin Forms 的列表视图单元格的选定项目上的带有单选按钮的 Checked 绑定?
- matlab - 左矩阵除以向量
- angularjs - 如何使用量角器测试是否显示 AngularJS md-tooltip
- ruby - Ruby popen3 - 如何防止重复写入标准输入导致超时?
- office-js - Microsoft Teams 中未显示管理员管理的 Office Web 插件
- php - 事务在 CodeIgniter 中无法正常工作