ili*_*ask 7 java hibernate jpa one-to-many
我有两个型号.
@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;
}
Run Code Online (Sandbox Code Playgroud)
做什么JPA /休眠批注我需要把上面homeAddress,schoolAddress并且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;
Run Code Online (Sandbox Code Playgroud)
和
@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;
Run Code Online (Sandbox Code Playgroud)
yealds 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".
还考虑了移动JoinColumns到Student平板电脑,但我不确定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;
Run Code Online (Sandbox Code Playgroud)
使用此功能,当在DB中存储模型时,即使存储了两端(Student和Address模型),student_homeAddress_id和student_schoolAddress_id也始终为null.
我的想法是,在Address桌面上将有3个额外的列:student_homeAddress_id(homeAddress的Student表中Student的id),student_schoolAddress_id(studentAddress的Student表中Student的id)和students_index(0基于students列表的位置).这应该足够了,对吗?
有任何想法吗?
非常感谢!
我们尝试了 mael 的建议,但无法实现。
我们最终遵循了这个可行的方法。
换句话说,我们有OneToMany关系:
在Student:
protected List<AddressStudentAssociation> addresses;
Run Code Online (Sandbox Code Playgroud)
在Address:
protected List<AddressStudentAssociation> students;
Run Code Online (Sandbox Code Playgroud)
并在AddressStudentAssociation:
@ManyToOne
@PrimaryKeyJoinColumn(name="STUDENTID", referencedColumnName="id")
private Student student;
@ManyToOne
@PrimaryKeyJoinColumn(name="ADDRESSID", referencedColumnName="id")
private Address address;
Run Code Online (Sandbox Code Playgroud)
加上一个参数以将一个地址与另一个地址分开 ( isHome)。
最后,在里面Student我们有public Address getHomeAddress()它遍历addresses列表并返回正确的地址。我们还必须使用注释才能使其工作。通常不是最佳的,但它有效,我们已经花了太多时间试图让事情发挥作用。:|
| 归档时间: |
|
| 查看次数: |
19319 次 |
| 最近记录: |