什么情况下是多对多?
举个例子:一个老师可以教多个学生,每个学生也可以被多个老师教。这就是多对多的情况。
在数据库表中这种关系该怎么设计?很简单,加一张中间表。
设计模型:
table_student id<int> <pk>
table_teacher id<int> <pk>
中间表:
T_S t_id<int> <pk,fk2> s_id<int> <pk,fk1>
比如老师2教学生1,在中间表中就存2,1
老师2教学生3,在中间表中就存2,3
这就可以表示多对多的关系了。
hibernate中利用Annotation注解实现:
Student.java:
package cn.edu.hpu.many2many; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="m_student") public class Student { private int id; private String name; @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Teacher.java:
package cn.edu.hpu.many2many; import java.util.HashSet; import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; import cn.edu.hpu.many2many.Student; @Entity @Table(name="m_teacher") public class Teacher { private int id; private String name; private Set<Student> students=new HashSet<Student>(); //选择set的原因是因为,set互相之间不会有重复的 //跟数据库模型比较匹配 @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @ManyToMany public Set<Student> getStudents() { return students; } public void setStudents(Set<Student> students) { this.students = students; } }
生成的建表语句:
create table m_student (
id integer not null auto_increment,
name varchar(255),
primary key (id)
)
create table m_teacher (
id integer not null auto_increment,
name varchar(255),
primary key (id)
)
create table m_teacher_m_student (
m_teacher_id integer not null,
students_id integer not null,
primary key (m_teacher_id, students_id)
)
alter table m_teacher_m_student
add index FK9536C8FA2DA52D4 (m_teacher_id),
add constraint FK9536C8FA2DA52D4
foreign key (m_teacher_id)
references m_teacher (id)
alter table m_teacher_m_student
add index FK9536C8FA34A96CA5 (students_id),
add constraint FK9536C8FA34A96CA5
foreign key (students_id)
references m_student (id)
除了m_student和m_teacher表以外,还生成了一张m_teacher_m_student表,
里面的m_teacher_id属性和students_id分别添加了外键关联。
我如果想改变一下它默认生成表的名字,以及中间那张表默认列的名字,
这个时候怎么做?
做法:
一个Annotation属性叫做:@JoinTable(name="t_s")
加在@ManyToMany下面:
@ManyToMany
@JoinTable(name="t_s")
public Set<Student> getStudents() {
return students;
}
改中间表的字段名称:
@ManyToMany
@JoinTable(name="t_s",
joinColumns={@JoinColumn(name="teacher_id")},//指明的是当前这个实体类的表的名字(加s防止联合主键)
inverseJoinColumns={@JoinColumn(name="student_id")}//逆转的、对方的的表名(所对应的另一张表)
)
public Set<Student> getStudents() {
return students;
}
不需要背,会查文档即可。
转载请注明出处:http://blog.csdn.net/acmman