简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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