ManyToMany双向外键关联(基于注解)的映射案例(简单版)

时间:2020-12-04 20:37:11

学生和老师就是多对多的关系,一个学生有多个学生,一个老师也有多个学生,这里的多对多映射采用中间表连接的映射策略,建立中间表的映射策略,建立中间表分别引入俩边的主键作为外键。通过中间表映射俩个表之间的关系。

下面就以学生类和老师类为例介绍多对多的映射关系的实例

Students类

package mtm_bfk;

import java.io.Serializable;
import java.util.Date;
import java.util.Set;

import javax.persistence.Entity; //JPA注解
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;




/**
* 学生类
* @ClassName: Students
* @Description: 学生类
* @author: Administrator
* @date: 2016年3月28日 下午5:01:03
*/

//@Entity(name="t_students") //使用了这个注解以后 这个属性就可以映射成关系型数据库中的一张叫做t_students的表 没有name的话就默认生成students
@Entity(name="t_students")
public class Students implements Serializable{

private static final long serialVersionUID = 1L;

private int sid;//主键
private String gender; //性别
private Date brithday;//生日
private Set<Teachers> teachers;//学生持有教师的集合



public Students( String gender,
Date brithday) {
//super();

this.gender = gender;
this.brithday = brithday;

}
@Id //主键
@GeneratedValue //数据库自增
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}


public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getBrithday() {
return brithday;
}
public void setBrithday(Date brithday) {
this.brithday = brithday;
}

@ManyToMany //多对多外键关联的配置
@JoinTable(name="teachers_students" ,//中间表的表名
joinColumns={@JoinColumn(name="sid")},//本表的主键
inverseJoinColumns={@JoinColumn(name="tid")})//所映射表的主键
public Set<Teachers> getTeachers() {
return teachers;
}
public void setTeachers(Set<Teachers> teachers) {
this.teachers = teachers;
}



}

Teachers实体类

package mtm_bfk;

import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;


/**
* @ClassName: Teachers
* @Description: 教师的实体类
* @author: Administrator
* @date: 2016年6月12日 下午7:52:59
*/

@Entity
public class Teachers {
@Id
@GeneratedValue//(generator="tid")
// @GenericGenerator(name="tid",strategy="assigned") //代表数据库非自增
@Column(length=8)
private int tid;//教师的编号
private String tname;//教师的名字
@ManyToMany(mappedBy="teachers")//把主控方交给学生
private Set<Students>stus;//教师持有的学生的集合

public Teachers() {
//super();
}

public Teachers(String tname) {
// super();
this.tname = tname;
}


public int getTid() {
return tid;
}


public void setTid(int tid) {
this.tid = tid;
}


public String getTname() {
return tname;
}
public void setTname(String tname) {
this.tname = tname;
}
}

hibernate的配置文件

<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">


<hibernate-configuration>
<session-factory>
<!-- 数据库的相关配置 -->
<property name="connection.username">用户名</property>
<property name="connection.password">密码</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql:///test?useUnicode=true&amp;characterEncoding=UTF-8</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- 开发常用的参数 -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- 下面的这个配置是表示可以使用getCurrentSessoion的方式打开会话 -->
<property name="hibernate.current_session_context_class">thread</property>

<!-- <mapping class="com.entity.Students" /> -->
<mapping class="mtm_bfk.Students"/>
<mapping class="mtm_bfk.Teachers"/>

</session-factory>
</hibernate-configuration>

TestStudents测试类

package mtm_bfk;




import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;

import mtm_bfk.Students;


public class TestStudents {
@SuppressWarnings("unused")
@Test
//生成表结构
public void textSchemaExport(){
//创建配置对象
Configuration config = new Configuration().configure();
//创建服务对象
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
//创建sessionFactory
SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
//创建session对象
Session session = sessionFactory.getCurrentSession();
//创建SchemaExport对象
SchemaExport export = new SchemaExport(config);

export.create(true, true);//第一个true是生成表结构第二个是输出sql语句
}
@Test
public void testSaveStudents(){
//创建配置对象
Configuration config = new Configuration().configure();
//创建服务对象
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
//创建sessionFactory
SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
//创建session对象
Session session = sessionFactory.getCurrentSession();
//创建事物对象
Transaction tx = session.beginTransaction();
//创建教师对象
Teachers t1 = new Teachers("123");
Teachers t2 = new Teachers("789");
Teachers t3 = new Teachers("1235");
Teachers t4 = new Teachers("784");


Students s = new Students("nan",new Date());
Students s1 = new Students("nv",new Date());
Students s2 = new Students("na",new Date());
//创建俩个集合对象
Set<Teachers> set1 = new HashSet<Teachers>();
set1.add(t1);
set1.add(t2);
Set<Teachers> set2 = new HashSet<Teachers>();
set2.add(t3);
set2.add(t4);

s.setTeachers(set2);
s1.setTeachers(set1);
s2.setTeachers(set2);
//先保存教师
session.save(t1);
session.save(t2);
session.save(t3);
session.save(t4);

session.save(s);
session.save(s1);
session.save(s2);

tx.commit();
sessionFactory.close();
}
}

以上配置就实现了多对多的外键关联了
这里面有多种映射关系的配置http://download.csdn.net/detail/u013412790/9571110