如何在使用JpaRepository和Spring Boot的方法中找到一个没有参数的对象列表。

huangapple go评论65阅读模式
英文:

How find an object list without a parameter in method with JpaRepository, Spring-boot

问题

需要使用JpaRepository获取对象列表,但在某些情况下,方法中可能缺少一个变量。例如:

如果我需要 findByNombreCursoContainsIgnoreCaseAndAreaBean但我没有变量 **Area**我该怎么办为每个查询情况创建特定的方法吗是否存在一种方法我可以将Area的值传递为null并获得所有领域的查询

将会是

findByNombreCursoContainsIgnoreCaseAndAreaBean("example", null);

通过这样可以获取所有具有 "example" 和所有领域的列表

我在尝试做什么我在我的应用程序中想要实现一个搜索功能我认为这不是最优解

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);
    }
                
}
英文:

I need to get an object list with JpaRepository but in some cases I don`t have one of the variables in method. For example:

如何在使用JpaRepository和Spring Boot的方法中找到一个没有参数的对象列表。

If I need findByNombreCursoContainsIgnoreCaseAndAreaBean but I don´t have the variable Area, what I should do? create specifics methods for each case of my queries? Exists a method in which I can pass null value for Area and get the query for all the areas?

will be

findByNombreCursoContainsIgnoreCaseAndAreaBean(&quot;example&quot;, null);

and with this get all the list with "example" and all areas.

What I'm trying to do? A searcher in my application: I think this is not optimum:

public Page&lt;Curso&gt; searcher(String nombreCurso, Area area, int activo, Pageable pageable){		
	try {
		if(nombreCurso.isEmpty() &amp;&amp; area!=null &amp;&amp;  area.getIdArea() == 0 &amp;&amp; activo == 2) {
			return getAll(pageable);
		} if(area.getIdArea() == 0 &amp;&amp; activo == 2) { 
			return repo.findByNombreCursoContainsIgnoreCase(nombreCurso, pageable);
		} if(activo != 2 &amp;&amp; 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);
	}
				
}	

答案1

得分: 1

方法1尝试使用 Optional

    findByNombreCursoContainsIgnoreCaseAndAreaBean (.., Optional&lt;Area&gt; areaOption,.){
        // 一些代码
        if (optionalArgument.isPresent()) {
            进行某些操作(optionalArgument.get());
        } else {
            进行其他操作();
        }
    }

方法2从 REST 接收数据
       1. 使用可选的请求参数设置默认值然后调用相应的方法

    @GetMapping("/api/foos")
    @ResponseBody
    public void getFoos(@RequestParam(required = false) String id) { 
       进行某些操作(id);       
    }

**或者**

2. 使用默认值
为请求参数设置默认值

    @GetMapping("/api/foos")
    @ResponseBody
    public void getFoos(@RequestParam(defaultValue = "test") String id) {
       进行某些操作(id); 
    }
英文:

Way 1 . Try Optional

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

Way 2: While receiving data from REST <br> <hr>
1. Optional Request Parameters using ie set the default value and then call respective methods

@GetMapping(&quot;/api/foos&quot;)
@ResponseBody
public void getFoos(@RequestParam(required = false) String id) { 
   doSomething(id);       
}

OR

  1. Using Default Value <br>
    A Default Value for the Request Parameter

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

答案2

得分: 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

英文:

You can use org.springframework.data.domain.Example. An entity model is put into example and queried by that. Since only nombre field is set as below, query criteria is build considering just that field. If you set more fields other than null, those are also added to search criteria

Curso curso = new Curso();
curso.setNombre(5);
Page&lt;Curso&gt; page = cursoRepository.findAll(Example.of(curso),pageable);

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

huangapple
  • 本文由 发表于 2020年9月29日 19:14:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/64118453.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定