通常为了实现entity class的双向association,每添加一组实例在java中需要两行代码:
persion.getAddresses().add(address);
address.getPersons().add(person);
但对Hibernate而已,上面的代码会被转化为两条insert语句,
为了避免这样的情况出现需要定义inverse属性,告诉Hibernate persion和address之间的关系:
// !file: Person.class
public class Person {
// ...
@ManyToMany(
targetEntity= Address.class,
cascade = CascadeType.ALL,
)
@JoinTable(
name="persion_address",
joinColumns= {@JoinColumn(name="person_id")},
inverseJoinColumns= {@JoinColumn(name="address_id")}
)
private Set<Address> adressses = new HashSet<Address> (0);
// ...
}
// !file: Address.class
public class Address {
// ...
@ManyToMany(
targetEntity= Persion.class,
cascade = CascadeType.ALL,
mappedBy = "addresses"
)
private Set<Person> persons = new HashSet<Person>();
// ...
}
上面的两个annotation告诉Hibernate,Person是主,对Address中persons属性的修改将不会产生SQL语句。
Hibernate里,如果是Many-to-many的关系,可以任意设置主class。
通常,还可以将添加删除关系的代码包装起来:
// !file: Person.class
public class Person {
// ...
public void addAddress(Address address) {
this.getAddresses().add(address);
address.getPersons().add(this);
}
public void removeAddress(Address address) {
this.getAddresses().remove(address);
address.getPersons().remove(this);
}
//...
}
posted on 2007-03-27 21:18
hijeff 阅读(351)
评论(0) 编辑 收藏 所属分类:
Hibernate