简体   繁体   English

具有可选参数的JPA /休眠自定义查询

[英]JPA/Hibernate Custom Queries with optional parameters

I have an Entity 我有一个实体

@Entity
@Table(name = "EVENT")
public class Event {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    @Column(name = "EVENT", columnDefinition="VARCHAR(100)", nullable = false)
    private String event;

    @Column(name = "DATE", columnDefinition="DATETIME", nullable = false)
    @Convert(converter = InstantConverter.class)
    private Instant date;
}

And a SearchParams class where all of the fields are optional 还有一个SearchParams,其中所有字段都是可选的

public class SearchParams {
    private Long id;
    private Instant startDate;
    private Instant endDate;
    private String event;

    public Optional<Long> getID() {
        return Optional.ofNullable(id);
    }
    // ... Similar for other fields ...
}

I would like to be able to search like: 我希望能够像这样进行搜索:

public List<Event> search(SearchParams searchParams) {
    // Do something with Entity Manager/another hibernate class to create a custom query based off the search params.
    return events;
}

What's the easiest way to achieve this in JPA? 在JPA中最简单的方法是什么? Or is this not the right framework to use? 还是这不是使用正确的框架?

I could always resort to sql string building but its not a nice way of doing it. 我总是可以求助于sql字符串构建,但是这样做不是一个好方法。

As far as remember JPA has method where, which takes array of Predicates as parameter. 据记住,JPA具有方法where,该方法将谓词数组作为参数。

So what you could do is create dynamic list of predicates from your params and then pass it to your query. 因此,您可以做的是根据您的参数创建谓词的动态列表,然后将其传递给查询。

so your code will be something like that 所以你的代码将是这样的

List<Predicate> predicates= new ArrayList<>();
if (!searchParams.getId().isEmpty()){
predicates.add(cb.equal(root.get("id"), searchParams.getId());
}
....
query.where(predicates.toArray(new Predicate[predicates.size()]));

The Spring Data JPA query-by-example technique uses Example s and ExampleMatcher s to convert entity instances into the underlying query. Spring Data JPA示例查询技术使用ExampleExampleMatcher将实体实例转换为基础查询。 The current official documentation clarifies that only exact matching is available for non-string attributes. 当前的官方文档阐明了仅精确匹配可用于非字符串属性。 Since your requirement involves a Date field, you can only have exact matching with the query-by-example technique. 由于您的要求涉及“日期”字段,因此只能与“按示例查询”技术完全匹配。

Refer https://stackoverflow.com/a/39555487/4939174 请参阅https://stackoverflow.com/a/39555487/4939174

You can also refer this link for Spring Data JPA - Specifications and Querydsl 您也可以参考此链接获取Spring Data JPA-规范和Querydsl

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM