在查询中映射复合外键



Hibernate似乎无法在我的JPA查询中找到复合外键conceptPk。如何让hibernate识别复合外键?

以下JPA:

@SuppressWarnings("unchecked")
public Collection<SnomedDescription> findDescriptionForConcept(SnomedConcept conc) {
    Query query = this.em.createQuery("SELECT descr FROM SnomedDescription descr WHERE descr.concept =:cid");
    query.setParameter("cid", conc);
    return query.getResultList();
}

正在生成以下hibernate SQL,这表明hibernate不识别嵌入的键:

select snomeddesc0_.effectiveTime as effectiv1_60_,
 snomeddesc0_.id as id2_60_,
 snomeddesc0_.active as active3_60_,
 snomeddesc0_.inSnapshot as inSnapsh4_60_,
 snomeddesc0_.languageCode as language5_60_,
 snomeddesc0_.moduleId as moduleId6_60_,
 snomeddesc0_.Term as Term7_60_
 from sct2_description snomeddesc0_
 where (snomeddesc0_.effectiveTime, snomeddesc0_.id)=(?, ?)

可以看到,hibernate试图在where子句中映射descriptionPK,而它应该在where子句中映射description.concept.conceptPk。我该如何解决这个问题?

确保在所有实体中实现适当的equals/hashcode方法,特别是Concept和ConceptKey,以解决您遇到的问题。

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result
            + ((conceptPk == null) ? 0 : conceptPk.hashCode());
    return result;
}
@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    Concept other = (Concept) obj;
    if (conceptPk == null) {
        if (other.conceptPk != null) {
            return false;
        }
    } else if (!conceptPk.equals(other.conceptPk)) {
        return false;
    }
    return true;
}

最新更新