JPA 2:在ManyToMany中使用额外字段

时间:2015-09-22 06:40:10

标签: java hibernate jpa jpa-2.1 hibernate-5.x

我有一个ManyToMany,我已经像这样映射了question

请注意,为简单起见,我删除了样板

@Entity
class Person {

    @OneToMany(mappedBy = "person")
    @OrderBy("sort")
    private List<PersonAddress> adresses = new ArrayList<>();

}

@Entity
class PersonAdress {
    @EmbeddedId
    private PersonAdressId id;
    @Column
    private int sort;

    @ManyToOne
    private Person person;

    @ManyToOne
    private Address address;
}

@Entity
class Address {
    @OneToMany(mappedBy = "address")
    @OrderBy("sort")
    private List<PersonAddress> persons = new ArrayList<>();
}

@Embeddable
public class PersonAdressId implements Serializable {
    @Column(name = "person_id")
    private long personId;
    @Column(name = "address_id")
    private long addressId;
}

我正在尝试获取person的所有地址,并按sort属性排序。 但由于某些原因,我得到了例外,或者我没有对它进行排序。

我尝试了以下内容:

"select p from Person p where p.id=pid join fetch p.address a order by a.sort"

我也尝试过:

Person person = entityManager.find(Person.class, personId);
person.getAddress() //<-- This should use the @OrderBy, but I don't get it ordered nor does it print out order by in the output

有人能说出为什么它无法正常工作吗?

2 个答案:

答案 0 :(得分:0)

您是否尝试过以下查询:

Select p From Person p Left Join p.adresses a Where p.id = :pid Order By a.sort

有关详细信息,请参阅HQL reference

答案 1 :(得分:0)

首先,您的映射是错误的:您想要Person和Address之间的多对多关联?那就是为什么你把PersonAddress实体放在中间?

  • 在类Person中,它应该是:

    @OneToMany(mappedBy = "person") private List<PersonAddress> personAdresses = new ArrayList<>();

  • 在课程地址中,应该是:

    @OneToMany(mappedBy = "address") private List<PersonAddress> personAddresses = new ArrayList<>();

只有这样,您的排序才会起作用,因为它是PersonAddress实体的成员