JPQL 计算 OneToMany 关系中多个子对象匹配的父对象

JPQL count Parent Objects on Multiple Children Match in OneToMany Relationship

在 JavaEE JPA Web 应用程序中,Feature 实体与 Patient 实体具有双向 ManyToOne 关系。我想编写一个查询来计算具有一个或多个匹配条件特征的患者的数量。我使用 EclipseLink 作为 Persistence Provider。

例如,我想计算具有 'variableName' = 'Sex' 和 'variableData' = 'Female' 特征以及 [= 另一个特征的患者数量25=] = 'smoking' 和 'variableData' = 'yes'.

如何编写 JPQL 查询来获取患者数量?

在第一个答案之后,我尝试了这个查询,没有给出任何预期的结果。

public void querySmokingFemales(){
    String j = "select count(f.patient) from Feature f "
            + "where ((f.variableName=:name1 and f.variableData=:data1)"
            + " and "
            + " (f.variableName=:name2 and f.variableData=:data2))";
    Map m = new HashMap();
    m.put("name1", "sex");
    m.put("data1", "female");
    m.put("name2", "smoking");
    m.put("data2", "yes");
    count = getFacade().countByJpql(j, m);
}

Patient实体如下

@Entity
public class Patient implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    @OneToMany(mappedBy = "patient")
    private List<Feature> features;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }



    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Patient)) {
            return false;
        }
        Patient other = (Patient) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "entity.Patient[ id=" + id + " ]";
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Feature> getFeatures() {
        return features;
    }

    public void setFeatures(List<Feature> features) {
        this.features = features;
    }

}

这是功能实体。

@Entity
public class Feature implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String variableName;
    private String variableData;
    @ManyToOne
    private Patient patient;



    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Feature)) {
            return false;
        }
        Feature other = (Feature) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "entity.Feature[ id=" + id + " ]";
    }

    public String getVariableName() {
        return variableName;
    }

    public void setVariableName(String variableName) {
        this.variableName = variableName;
    }

    public String getVariableData() {
        return variableData;
    }

    public void setVariableData(String variableData) {
        this.variableData = variableData;
    }

    public Patient getPatient() {
        return patient;
    }

    public void setPatient(Patient patient) {
        this.patient = patient;
    }

}

对于单个特征计数你可以使用这个

select count(f.patient) from Feature f where f.variableName=:name and f.variableData:=data

两个特征计数

select count(distinct p) from Patient p, Feature f1, Feature f2 
where 
  p.id=f1.patient.id and p.id=f2.patient.id and 
  f1.variableName=:name1 and f1.variableData:=data1 and 
  f2.variableName=:name2 and f2.variableData:=data2

多特征计数 解决方案有点棘手。 org.springframework.data.jpa.domain.Specification可以用

    public class PatientSpecifications {
      public static Specification<Patient> hasVariable(String name, String data) {
        return (root, query, builder) ->  {
                    Subquery<Fearure> subquery = query.subquery(Fearure.class);
                    Root<Fearure> feature = subquery.from(Fearure.class);

                    Predicate predicate1 = builder.equal(feature.get("patient").get("id"), root.get("id"));

                    Predicate predicate2 = builder.equal(feature.get("variableName"), name);
                    Predicate predicate3 = builder.equal(feature.get("variableData"), data);

                    subquery.select(operation).where(predicate1, predicate2, predicate3);

                    return builder.exists(subquery);
        }
      }
    }

然后你的 PatientRepository 必须扩展 org.springframework.data.jpa.repository.JpaSpecificationExecutor<Patient>

@Repository
public interface PatientRepository 
    extends JpaRepository<Patient, Long>, JpaSpecificationExecutor<Patient> {

}

您的服务方式:

@Service
public class PatientService {    

   @Autowired
   PatientRepository patientRepository;

   //The larger map is, the more subqueries query would involve. Try to avoid large map
   public long countPatiens(Map<String, String> nameDataMap) {
         Specification<Patient> spec = null;

         for(Map.Entry<String, String> entry : nameDataMap.entrySet()) {
            Specification<Patient> tempSpec = PatientSpecifications.hasVariable(entry.getKey(), entry.getValue());
            if(spec != null)
              spec = Specifications.where(spec).and(tempSpec);
            else spec = tempSpec;

         }

         Objects.requireNonNull(spec);

         return patientRepository.count(spec);        
    }
}

我们也处理了两个特征的相同情况,在提取 ID 之后,我们使用了嵌套循环并计算了公共计数的数量。这是资源密集型的,答案中的这两个特征查询帮助很大。

可能需要重新设计 Class 结构以便查询更容易。