Hibernate(JPA)多个@OneToMany用于同一模型

我有两个模型。

@Entity

public class Student

{

@Id

@GeneratedValue(strategy=GenerationType.AUTO)

protected long id;

@?

protected Address homeAddress;

@?

protected Address schoolAddress;

}

@Entity

public class Address

{

@Id

@GeneratedValue(strategy=GenerationType.AUTO)

protected long id;

@?

protected List<Student> students;

}

什么JPA / Hibernate注解,我需要把上面homeAddressschoolAddress并且students使协会工作?

当然,我尝试了很多事情,但没有任何效果。例如,设置

    @ManyToOne

@JoinColumn (name="student_homeAddress_id", updatable = false, insertable = false)

protected Address homeAddress;

@ManyToOne

@JoinColumn (name="student_schoolAddress_id", updatable = false, insertable = false)

protected Address schoolAddress;

    @OneToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}, fetch = FetchType.EAGER)

@JoinColumns({

@JoinColumn(name = "student_homeAddress_id", referencedColumnName = "student_homeAddress_id"),

@JoinColumn(name = "student_schoolAddress_id", referencedColumnName = "student_schoolAddress_id")})

@IndexColumn(name="students_index")

protected List<Student> students;

ald Unable to find column with logical name: student_homeAddress_id in

org.hibernate.mapping.Table(Address) and its related supertables and secondary

tables。也尝试使用,mappedBy但是只接受一个参数(不能这样做mappedBy="student_homeAddress_id,

student_schoolAddress_id"

还考虑过将其移动JoinColumnsStudent平板电脑上,但是我不确定OneToMany和ManyToOne的注释应该是什么样,因为我在那里有多个地址,而JoinColumns并没有多大意义。

起作用但未创建关联的事物有:

    @OneToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}, fetch = FetchType.EAGER)

@JoinColumn(name="address_id")

@IndexColumn(name="students_index")

protected List<Student> students;

使用此方法,在将模型存储在数据库中时,即使存储了两端(Student and

Address模型),student_homeAddress_id和student_schoolAddress_id也始终为空。

我的想法是,在Address表上将有3个额外的列:student_homeAddress_id(homeAddress在Student表中的Student的ID),student_schoolAddress_id(在schoolAddress的Student表中的Student的id)和students_index(0

students列表中基于位置的位置)。这样就足够了,对吗?

有任何想法吗?

非常感谢!

回答:

我们尝试了梅尔的建议,但未能成功。

我们最终遵循了这一行之有效的方法。

换句话说,我们有OneToMany关系:

Student

protected List<AddressStudentAssociation> addresses;

Address

protected List<AddressStudentAssociation> students;

并继续AddressStudentAssociation

@ManyToOne

@PrimaryKeyJoinColumn(name="STUDENTID", referencedColumnName="id")

private Student student;

@ManyToOne

@PrimaryKeyJoinColumn(name="ADDRESSID", referencedColumnName="id")

private Address address;

加上用于将一个地址与另一个地址(isHome)分开的参数。

最后,在内部Studentpublic Address

getHomeAddress()一个遍历addresses列表并返回正确地址的地址。我们还必须使用注释来使其起作用。一般而言,它不是最佳方法,但是它可以工作,并且我们已经花了太多时间试图使事情起作用。:|

以上是 Hibernate(JPA)多个@OneToMany用于同一模型 的全部内容, 来源链接: utcz.com/qa/420116.html

回到顶部