简体   繁体   中英

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

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? 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.

As far as remember JPA has method where, which takes array of Predicates as parameter.

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. 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

You can also refer this link for Spring Data JPA - Specifications and Querydsl

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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