hibernate的多对多映射没有太多选择,只能通过中间表来配置关联关系。
中间表如果没有其他属性,只有外键关联的话,那么只需要在两个类中添加set属性,然后在xml配置文件中添加set条目即可。
如果中间表有其他属性,则需要给中间表也创建一个持久层类,然后两个关联类分别与其建立一对多关联
例子如下:
两个关联表示user和course,中间表为user_course
user类中添加
private Set<UserCourse> usercourses = new HashSet<UserCourse>();
public Set<UserCourse> getUsercourses() {
return usercourses;
}
public void setUsercourses(Set<UserCourse> usercourses) {
this.usercourses = usercourses;
}
user.hbm.xml中添加
<set name="usercourses" order-by="id" inverse="true">
<key column="userid"></key>
<one-to-many class="com.test.po.UserCourse"/>
</set>
course类中添加
private Set<UserCourse> usercourses = new HashSet<UserCourse>();
public Set<UserCourse> getUsercourses() {
return usercourses;
}
public void setUsercourses(Set<UserCourse> usercourses) {
this.usercourses = usercourses;
}
course.hbm.xml中添加
<set name="usercourses" order-by="id" inverse="true">
<key column="courseid"></key>
<one-to-many class="com.test.po.User" />
</set>
usercourse类中添加
private User user;//外键,用户表
private Course course;//外键,课程表
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
usercourse.hbm.xml中添加
<many-to-one name="user" class="com.test.po.User" column="userid"></many-to-one>
<many-to-one name="course" class="com.test.po.Course" column="courseid"></many-to-one>
现在就能实现两个表的多对多关联了。