Man Shen Man Shen - 2 months ago 12x
reST (reStructuredText) Question

Is it possible to build customized query at run time in Spring Boot?

This is what I am trying to do,

I have a entity,

public class JobEntity {

private Long id;

private Project project;

private JobType jobType;

private JobStatus jobStatus;

private Date createTime;

I know I could customize one query in repository, but that is just one fixed query. I hope to export some RESTful api, like below,


Those params should not be forcing required, and can easily use any of them to do the query, like


Is there an elegant way to implement this?


You could work with the specification API of Spring, which is a wrapper to the JPA criteria API. Make sure your repository extends from JpaSpecificationExecutor<JobEntity>

An example specification would be:

public class JobEntitySpecifications {
    public static Specification<JobEntity> withProject(Project project) {
        if (project == null) {
            return null;
        } else {
            return (root, query, cb) -> cb.equal(root.get("project"), project);

    public static Specification<JobEntity> withJobType() { ... }
    public static Specification<JobEntity> withJobStatus() { ... }
    public static Specification<JobEntity> withCreateTime() { ... }

Make sure you return null when no project code/job type/... is given so that it will be ignored in your query.

Now you can use this:


You can make it look even better if you use static imports here.