简体   繁体   English

一对多关系不同的选择

[英]One to many relation different option

i am developing an sample application using hibernate. 我正在使用休眠模式开发示例应用程序。 Its going quite smooth, but i have one small query regarding one to many relation. 它进行得很顺利,但是我有一个关于一对多关系的小查询。 I have seen there are 2 different ways of specifying the relation 我已经看到了两种指定关系的方式

@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "STUDENT_PHONE", joinColumns = { @JoinColumn(name = "STUDENT_ID") },     inverseJoinColumns = { @JoinColumn(name = "PHONE_ID") })
public Set<Phone> getStudentPhoneNumbers() { 
return this.studentPhoneNumbers;
}

the other way is 另一种方法是

@OneToMany(fetch=FetchType.EAGER)
@JoinColumn(name="PERSON_ID", nullable=false)
public Set<Address> getAddresses() {
    return addresses;
}

which is more efficient and when to use which method. 哪种方法更有效以及何时使用哪种方法。

The second one is probably a bit more efficient, because it needs one join less than the first one. 第二个连接可能效率更高,因为它需要的连接比第一个连接少。

But it couples the many side (address) to the one side (person) by requiring a foreign key in the address table. 但是它通过在地址表中要求外键将多面(地址)耦合到另一面(人)。 That is in contradiction with the fact that the association is unidirectional (address doesn't know about its person in the object model). 这与关联是单向的(地址在对象模型中不知道它的人)这一事实相矛盾。

This is why the second one is the default for unidirectional one to many associations. 这就是为什么第二个是单向一对多关联的默认设置的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM