Is it possible to create an individual request at runtime in Spring Boot?

This is what I'm trying to do

I have an entity

@Entity public class JobEntity { @Id @GeneratedValue private Long id; @Enumerated(EnumType.STRING) private Project project; @Enumerated(EnumType.STRING) private JobType jobType; @Enumerated(EnumType.STRING) private JobStatus jobStatus; private Date createTime; } 

I know that I can configure one request in the repository, but this is just one fixed request. I hope to export some RESTful api as below,

 /search?project=""&jobType=""&jobStatue=""&createTime="" 

These parameters should not be forced and can easily use any of them to execute a request, for example

 /search?createTime=""... 

Is there an elegant way to implement this?

+1
java spring rest spring-boot spring-data-jpa
source share
2 answers

You can work with the Spring Specification API, which is a wrapper for the JPA criteria API criteria. Make sure your repository extends from JpaSpecificationExecutor<JobEntity>

Specification Example:

 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 the project code / job type / ... is not specified so that it is ignored in your request.

Now you can use this:

 repository.findAll(Specifications.where(JobEntitySpecifications.withJobType(jobType)) .and(JobEntitySpecifications.withJobStatus(jobStatus)) .and(JobEntitySpecifications.withProject(project)) .and(JobEntitySpecifications.withCreateTime(createTime))); 

You can make it even better if using static imports here.

+2
source share

Although he is not sure about the dynamic construction of the query, think that he would have eaten time to create the query using various mechanisms.

There is Elastic Search that helps in creating one.

One way is to set query values ​​by default. Since the remaining values ​​are enums, you can add another enumeration literal to each enumeration as ALL

something like Project.ALL, JobType.ALL, JobStatus.ALL . The internal static methods in the enumeration should be written as such when EVERYTHING is requested, then add all JobTypes / Project / JobStatus to the list.

A single standard query that can be written in place of a query request on the fly. This is easy for the API in terms of caching the query result.

Most RESTful search APIs, such as /search?project=""&jobType=""&jobStatus=""&createTime="" , work by default.

0
source share

All Articles