如何使用Spring Data REST进行高级搜索?

Ale*_*o C 13 java spring java-8 spring-data-rest

我的任务是使用Spring Data REST进行高级搜索.我该如何实现它?

我设法做了一个简单的搜索方法,就像这样:

public interface ExampleRepository extends CrudRepository<Example, UUID>{

    @RestResource(path="searchByName", rel="searchByName")
    Example findByExampleName(@Param("example") String exampleName);

}
Run Code Online (Sandbox Code Playgroud)

如果我必须简单地去网址,这个例子很有效:

.../api/examples/search/searchByName?example=myExample
Run Code Online (Sandbox Code Playgroud)

但是,如果要搜索多个字段,我该怎么做?

例如,如果我的Example类有5个字段,那么我应该使用所有possibiles文件进行高级搜索?

考虑一下这个:

.../api/examples/search/searchByName?filed1=value1&field2=value2&field4=value4
Run Code Online (Sandbox Code Playgroud)

还有这个:

.../api/examples/search/searchByName?filed1=value1&field3=value3
Run Code Online (Sandbox Code Playgroud)

我需要做些什么才能以适当的方式实现此搜索?

谢谢.

Jef*_*ima 8

我设法使用Query by Example实现了这一点。

假设您有以下模型:

@Entity
public class Company {

  @Id
  @GeneratedValue
  Long id;

  String name;
  String address;

  @ManyToOne
  Department department;

}


@Entity
public class Department {

  @Id
  @GeneratedValue
  Long id;

  String name;

}
Run Code Online (Sandbox Code Playgroud)

和存储库:

@RepositoryRestResource
public interface CompanyRepository extends JpaRepository<Company, Long> {
}
Run Code Online (Sandbox Code Playgroud)

(注意JpaRepository实现了QueryByExampleExecutor)。

现在你实现一个自定义控制器:

@RepositoryRestController
@RequiredArgsConstructor
public class CompanyCustomController {

  private final CompanyRepository repository;

  @GetMapping("/companies/filter")
  public ResponseEntity<?> filter(
      Company company,
      Pageable page,
      PagedResourcesAssembler assembler,
      PersistentEntityResourceAssembler entityAssembler
  ){

    ExampleMatcher matcher = ExampleMatcher.matching()
        .withIgnoreCase()
        .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);

    Example example = Example.of(company, matcher);

    Page<?> result = this.repository.findAll(example, page);

    return ResponseEntity.ok(assembler.toResource(result, entityAssembler));

  }
}
Run Code Online (Sandbox Code Playgroud)

然后您可以进行如下查询:

localhost:8080/companies/filter?name=google&address=NY
Run Code Online (Sandbox Code Playgroud)

您甚至可以查询嵌套实体,例如:

localhost:8080/companies/filter?name=google&department.name=finances
Run Code Online (Sandbox Code Playgroud)

为简洁起见,我省略了一些细节,但我在 Github 上创建了一个工作示例


Mar*_*rin 7

Spring 参考 文档和大量技术博客中广泛记载的查询方法的实现虽然相当多,但已经过时了.

由于您的问题可能是"如何在不声明大量findBy*方法的情况下使用任何字段组合执行多参数搜索?",答案是Querydsl,它得到了Spring的支持.


Fai*_*roz 7

Spring Data Rest已将QueryDSL与Web支持集成在一起,您可以将其用于高级搜索需求.您需要更改您的存储库以实现,QueryDslPredicateExecutor并且开箱即用.

以下是有关该功能的博客文章中的示例:

$ http :8080/api/stores?address.city=York    
{
    "_embedded": {
        "stores": [
            {
                "_links": {
                    …
                }, 
                "address": {
                    "city": "New York", 
                    "location": { "x": -73.938421, "y": 40.851 }, 
                    "street": "803 W 181st St", 
                    "zip": "10033-4516"
                }, 
                "name": "Washington Hgts/181st St"
            }, 
            {
                "_links": {
                    …
                }, 
                "address": {
                    "city": "New York", 
                    "location": { "x": -73.939822, "y": 40.84135 }, 
                    "street": "4001 Broadway", 
                    "zip": "10032-1508"
                }, 
                "name": "168th & Broadway"
            }, 
            …
        ]
    }, 
    "_links": {
        …
    }, 
    "page": {
        "number": 0, 
        "size": 20, 
        "totalElements": 209, 
        "totalPages": 11
    }
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*o C 6

我已经找到了该任务的可行解决方案。

@RepositoryRestResource(excerptProjection=MyProjection.class)
public interface MyRepository extends Repository<Entity, UUID> {

    @Query("select e from Entity e "
          + "where (:field1='' or e.field1=:field1) "
          + "and (:field2='' or e.field2=:field2) "
          // ...
          + "and (:fieldN='' or e.fieldN=:fieldN)"
    Page<Entity> advancedSearch(@Param("field1") String field1,
                               @Param("field2") String field2,
                               @Param("fieldN") String fieldN,
                               Pageable page);

}
Run Code Online (Sandbox Code Playgroud)

通过此解决方案,使用此基本 url:

http://localhost:8080/api/examples/search/advancedSearch
Run Code Online (Sandbox Code Playgroud)

我们可以对我们需要的所有字段进行高级搜索。

一些例子:

http://localhost:8080/api/examples/search/advancedSearch?field1=example
    // filters only for the field1 valorized to "example"

http://localhost:8080/api/examples/search/advancedSearch?field1=name&field2=surname
    // filters for all records with field1 valorized to "name" and with field2 valorized to "surname"
Run Code Online (Sandbox Code Playgroud)