这里使用学生选课作为例子。学生可以选择多门课程,一门课程可以被多个学生选择。有三个表,学生表、课程表、学生与课程关系的关联表。
学生
@Entity
@Table(name="student")
public class Student implements Serializable{
@Transient
private static final long serialVersionUID = 1L;
@Id
@Column(name="studentid")
@GeneratedValue(strategy=GenerationType.IDENTITY)//定义主键生成策略,不写的话中间表可能没有真实数据
private int studentid;
@Column(name="name")
private String name;
@Column(name="sex")
private String sex;
/**
* @ManyTOMany多对多映射
* @JoinTable添加关联表(name="关联表表名",joincolumns={@joincolumn(name="关联表外键字段名",referencedColumnName="主表的主键字段名")})
*/
@ManyToMany
@Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
@JoinTable(name="student_course",
joinColumns={@JoinColumn(name="studentid",referencedColumnName="studentid")},
inverseJoinColumns={@JoinColumn(name="courseid",referencedColumnName="id")})
/*
省略setter、getter
*/
课程
@Entity
@Table(name="course")
public class Course implements Serializable{
@Transient
private static final long serialVersionUID = 1L;
@Id
@Column(name="id")
private int courseid;
@Column(name="coursename",nullable=false,unique = true)
private String coursename;
@Column
private String isRequired;
public String getIsRequired() {
return isRequired;
}
public void setIsRequired(String isRequired) {
this.isRequired = isRequired;
}
@ManyToMany(mappedBy="courses")//由学生端维护中间表
/*@JoinTable(name="student_course",
joinColumns={@JoinColumn(name="courseid",referencedColumnName="id")},
inverseJoinColumns={@JoinColumn(name="studentid",referencedColumnName="studentid")})
两端都可以维护中间表*/
private List<Student> students;
/*
省略setter、getter
*/
}