【问题标题】:How find an object list without a parameter in method with JpaRepository, Spring-boot如何使用 JpaRepository,Spring-boot 在方法中查找没有参数的对象列表
【发布时间】:2020-09-29 11:14:10
【问题描述】:

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

如果我需要 findByNombreCursoContainsIgnoreCaseAndAreaBean 但我没有变量 Area,我应该怎么做?为我的每个查询案例创建具体方法?是否存在一种方法,我可以为 Area 传递 null 值并获取所有区域的查询?

将会

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

【问题讨论】:

    标签: java spring database spring-boot spring-data


    【解决方案1】:

    您可以使用 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

    【讨论】:

      【解决方案2】:

      方式 1 。尝试可选

      findByNombreCursoContainsIgnoreCaseAndAreaBean (..,(Optional<Area> areaOption,.){
          // some code
          if (optionalArgument.isPresent()) {
              doSomething(optionalArgument.get());
          } else {
              doSomethingElse();
          }
      }
      

      方式 2:从 REST 接收数据时


      1.可选的请求参数使用ie设置默认值,然后调用相应的方法
      @GetMapping("/api/foos")
      @ResponseBody
      public void getFoos(@RequestParam(required = false) String id) { 
         doSomething(id);       
      }
      

      1. 使用默认值
        请求参数的默认值

        @GetMapping("/api/foos") @ResponseBody public void getFoos(@RequestParam(defaultValue = "test") String id) { 做某事(id); }

      【讨论】:

      • Optional 类不能用作参数。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-29
      • 2020-11-28
      • 1970-01-01
      • 2021-08-18
      • 2018-10-30
      • 2018-01-13
      • 2020-05-31
      相关资源
      最近更新 更多