Hibernate标准按连接表列排序

时间:2015-09-22 02:07:31

标签: hql hibernate-criteria hibernate-entitymanager

我有通过person_membership表与manyToMany关系链接的成员资格和人员表。 person_membership表包括person_id,membership_id和sequence_number。 Membership实体具有以下代码以链接到person表。

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
        name = "person_membership", 
        joinColumns = { @JoinColumn(name = "membership_id", nullable = false, updatable = false) }, 
        inverseJoinColumns = { @JoinColumn(name = "person_id", nullable = false, updatable = false) }
)
public Set<Person> getPersons() {
    return this.persons;
}

使用以下代码通过条件检索成员资格:

Session session = getSession();
        Criteria c = session.createCriteria(Membership.class, "membership");
        c.add(Restrictions.eq("membershipNumber", membershipNumber));

        return (Membership) c.uniqueResult();

我想要做的是按person_membership.sequence_number对结果进行排序。我如何使用标准来做到这一点,或者可能有另一种方法可以做到这一点?

如果可能的话,我会采用一种漂亮,干净且不复杂的方式:)

1 个答案:

答案 0 :(得分:0)

如果您想在获取时订购人员,请提及&#34; sequenceNumber&#34;使用JPA @OrderBy注释的列

@OrderBy("sequenceNumber")
public Set<Person> getPersons() {

如果您想按person_membership.sequence_number订购所有会员资格,然后在结果中返回第一个或不同的会员资格,如下所示。

HQL

select distinct m 
from Membership m 
join m.persons p 
order by p.sequenceNumber;

标准

    Session session = getSession();
    Criteria c = session.createCriteria(Membership.class, "membership");
    c.createCriteria("membership.persons", "person");
    c.add(Restrictions.eq("membershipNumber", membershipNumber));
    c.addOrder(Order.asc("person.sequenceNumber"))
    c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)

    return (Membership) c.uniqueResult();