当前位置: 首页 > 知识库问答 >
问题:

Dynamic where JPA Spring Boot

师博
2023-03-14

我在Spring Boot应用程序中有一个表和Pojo,如下所示。

@Entity
@Table(name = "attendance_summary")
public class AttendanceSummary implements Serializable {

  @Id
  @SequenceGenerator(name = "attendance_summary_id_seq",
    sequenceName = "attendance_summary_id_seq",
    allocationSize = 1)
  @GeneratedValue(strategy = GenerationType.SEQUENCE,
    generator = "attendance_summary_id_seq")
  @Column(name = "id", updatable = false)
  public Integer id;

  @Column(name = "emp_id", nullable = false)
  public Integer empId;

  @Column(name = "designation_id")
  public Integer designationId;

  @Column(name = "designation_category_id")
  public Integer designationCategoryId;

  @Column(name = "department_id")
  public Integer departmentId;

  ......
}
public interface AttendanceSummaryRepository extends JpaRepository<Integer,AttendanceSummary>{
     List<AttendanceSummary> findByEmpIdAndDesignationId....(List<Integer> empIdList,List<Integer> designationIdList ... );
}
query= "Select * from attendance_summary where ";
if(empIdList != null)
    query = query + " emp_id in empIdList "
if(designationIdList != null)
    query = query + " designation_id in designationIdList "
 .....
 //You get the idea. 

对不起,我的英语不好,如果我不能正确地解释我的问题。

共有1个答案

孙熠彤
2023-03-14

看一下标准API。它允许您创建动态查询。

在您的示例中,与此类似的内容可以起作用:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<AttendanceSummary> query = cb.createQuery(AttendanceSummary.class);
Root<AttendanceSummary> root = query.from(AttendanceSummary.class);

List<Predicate> predList = new ArrayList<>();
if (empIdList != null) {
    predList.add(root.get('empId').in(empIdList));
}
if (designationIdList != null) {
    predList.add(root.get('designationId').in(designationIdList));
}
// ... You get the idea.

Predicate[] predicates = new Predicate[predList.size()];
predList.toArray(predicates);

query.where(predicates);

return entityManager.createQuery(query).getResultList();
 类似资料:

相关问答

相关文章

相关阅读