首页 > 解决方案 > 如何使用 JpaRepository,Spring-boot 在方法中查找没有参数的对象列表

问题描述

我需要使用 JpaRepository 获取对象列表,但在某些情况下,我没有方法中的变量之一。例如:

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);
    }
                
}   

标签: javaspringdatabasespring-bootspring-data

解决方案


您可以使用 org.springframework.data.domain.Example。以实体模型为例进行查询。由于只设置了 nombre 字段,因此仅考虑该字段来构建查询条件。如果您设置了除 null 以外的更多字段,这些字段也会添加到搜索条件中

Curso curso = new Curso();
curso.setNombre(5);
Page<Curso> page = cursoRepository.findAll(Example.of(curso),pageable);

https://www.baeldung.com/spring-data-query-by-example


推荐阅读