是否可以在 Spring Boot 中在运行时构建自定义查询? [英] Is it possible to build customized query at run time in Spring Boot?
问题描述
这就是我想要做的,
我有一个实体,
@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;
}
我知道我可以在存储库中自定义一个查询,但这只是一个固定查询.我希望导出一些 RESTful api,如下所示,
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,
/search?project=""&jobType=""&jobStatue=""&createTime=""
那些参数不应该是强制要求的,并且可以很容易地使用它们中的任何一个来进行查询,比如
Those params should not be forcing required, and can easily use any of them to do the query, like
/search?createTime=""...
有没有一种优雅的方式来实现这一点?
Is there an elegant way to implement this?
推荐答案
您可以使用 Spring 的规范 API,它是 JPA 标准 API 的包装器.确保您的存储库从 JpaSpecificationExecutor
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>
一个示例规范是:
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() { ... }
}
确保在未提供项目代码/作业类型/...时返回 null
,以便在查询中将其忽略.
Make sure you return null
when no project code/job type/... is given so that it will be ignored in your query.
现在你可以使用这个:
repository.findAll(Specifications.where(JobEntitySpecifications.withJobType(jobType))
.and(JobEntitySpecifications.withJobStatus(jobStatus))
.and(JobEntitySpecifications.withProject(project))
.and(JobEntitySpecifications.withCreateTime(createTime)));
如果你在这里使用静态导入,你可以让它看起来更好.
You can make it look even better if you use static imports here.
这篇关于是否可以在 Spring Boot 中在运行时构建自定义查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!