创建动态查询,根据多个where条件从db中获取条目

4dbbbstv  于 2021-07-16  发布在  Java
关注(0)|答案(3)|浏览(253)

以下是生成实体:

@Entity
@Table(name = "build")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Build {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Integer id;

    @ManyToOne(
            fetch = FetchType.EAGER,
            cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinColumn(name = "job_id", referencedColumnName = "id", nullable = false)
    private Job job;

    @Column(name = "build_url", nullable = false)
    private String buildUrl;

    @Column(name = "status")
    private String status;

    @Column(name = "name", nullable = false)
    private String name;
}

下面是我与db执行事务的存储库:

public interface BuildRepository extends CrudRepository<Build, Integer> {

    List<Build> findByStatus(@Param("status") String status);

    @Transactional
    @Modifying(flushAutomatically = true, clearAutomatically = true)
    @Query(value = "update Build set status = ?2 where id = ?1")
    void updateBuildStatus(int id, String status);
}

如果必须获取特定id的条目,可以在存储库中使用findbyid()。
现在,我想根据id、job和name从表中获取条目。id、作业和名称中至少有一个不为空。有人能帮我构建一个动态采石场来处理这个场景吗?

vecaoik1

vecaoik11#

您可以使用spring数据的规范或hibernate的criteriaapi来创建动态查询。
https://www.baeldung.com/rest-api-search-language-spring-data-specificationshttps://www.baeldung.com/hibernate-criteria-queries

2ledvvac

2ledvvac2#

感谢@yerlikayaoglu的回复。通过向我的存储库中添加以下方法解决了此问题:

@Query("select j FROM Build j where (:Id is null or j.id = :Id) and (:job is null or j.job = :job) and (:name is null or j.name = :name)")
        List<Build> findByIdAndJobAndName(
                @Param("Id") Integer Id,
                @Param("Job") JenkinsJob Job,
                @Param("Name") String Name);

这篇文章很有帮助:
https://www.baeldung.com/spring-data-jpa-null-parameters

to94eoyn

to94eoyn3#

您可以简单地使用这样一个库,它允许您构建非常高级的搜索查询(支持逻辑操作、比较、枚举、日期、联接、函数等):https://github.com/turkraft/spring-filter

相关问题