学IT就来ACCP教程网
您的位置:ACCP教程网图文教程JSP教程 ┳ 内容

Hibernate单向多对多

时间:2010-01-01 12:45:13 |来源:网络 |作者:秩名 |点击:

Hibernate单向多对多关联。如:一个学生对应多门课程,一门课程也对应多名学生。本例单向关联,只考虑学生到课程的一对多关联。
1、概述
a.实体类
public class Student{
    ......
    private Set<Course> courses;
    ......
}

public class Course{
    ......
}

b.数据库表
    Student与Course各对应一张数据库表,再建一张关联表student_course (studentid,courseid),保存多对多关联。其中,student_course表的主键为studentid与courseid的联合。

c.配置文件
Student.hbm.xml:
......
<set name="courses" table="student_course" cascade="all">
    <key column="studentid" />
    <many-to-many column="courseid" class="wintys.hibernate.manytomany.Course"/>
</set>
......

Course.hbm.xml:
......

2、实体类:
Student.java:

 

package wintys.hibernate.manytomany;

import java.util.Set;

/**
 * @version 2009-06-19
 * @author Winty (wintys@gmail.com)
 *
 */
public class Student {
    private Integer id;
    private String name;
    private Set<Course> courses;
   
    public Student(){
    }
   
    public Student(String name){
        this.name = name;
    }
                    
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Set<Course> getCourses() {
        return courses;
    }
    public void setCourses(Set<Course> courses) {
        this.courses = courses;
    }
}

Course.java:

 

package wintys.hibernate.manytomany;

import java.util.Set;

/**
 * @version 2009-06-19
 * @author Winty (wintys@gmail.com)
 *
 */
public class Course {
    private Integer id;
    private String name;
   
    public Course(){
    }
   
    public Course(String name){
        this.name = name;
    }
   
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

共 4 页
  • 1234
    顶一下
    (1)
    33.3%
    踩一下
    (2)
    66.7%
    loading.. 评论加载中....