Hibernate 多对多
最近学习hibernate 今天调试一个例子 实现多对多的 插入 采用中间表的形式 进行操作
代码如下:
teacher table
createtable`test`.`teacher`(
`tid`intnotnullauto_increment,
`tname`varchar(40),
primarykey(`tid`)
);create unique index `PRIMARY` on `test`.`teacher`(`tid`);
studnt table
createtable`test`.`student`(
`sid`intnotnullauto_increment,
`sname`varchar(40),
primarykey(`sid`)
);create unique index `PRIMARY` on `test`.`student`(`sid`);
stu_tea_tab table
createtable`test`.`stu_tea_tab`(
`tid`int,
`sid`int
);===========================
teacher.class
package com.test.beans;
import java.util.HashSet;import java.util.Set;
public class Teacher
{
private Integer tid;private String tname;
private Set students = new HashSet ( );
public Integer getTid()
{
returntid;
}public void setTid(Integer tid)
{
this.tid=tid;
}public String getTname() {
return tname; }
public void setTname(String tname) {
this.tname = tname; }
public Set getStudents() {
return students; }
public void setStudents(Set students) {
this.students = students; }
}
teacher 的配置文件:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
MappingfileautogeneratedbyMyEclipsePersistenceTools
--><hibernate-mapping>
<classname="com.test.beans.Teacher"table="teacher">
<idname="tid"type="java.lang.Integer">
<columnname="tid"></column>
<generatorclass="native"></generator>
</id>
<propertyname="tname"type="java.lang.String">
<columnname="tname"length="40"></column>
</property>
<setname="students"table="stu_tea_tab"inverse="true"cascade="save-update">
<keycolumn="tid"></key>
<many-to-manyclass="com.test.beans.Student"column="sid"></many-to-many>
</set>
</class></hibernate-mapping>
student.class
package com.test.beans;
import java.util.HashSet;import java.util.Set;
public class Student
{
privateIntegersid;
privateStringsname;
privateSetteachers=newHashSet();
publicStringgetSname()
{
returnsname;
}
publicvoidsetSname(Stringsname)
{
this.sname=sname;
}
publicIntegergetSid()
{
returnsid;
}
publicvoidsetSid(Integersid)
{
this.sid=sid;
}
publicSetgetTeachers()
{
returnteachers;
}
publicvoidsetTeachers(Setteachers)
{
this.teachers=teachers;
}
}student.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
MappingfileautogeneratedbyMyEclipsePersistenceTools
--><hibernate-mapping>
<classname="com.test.beans.Student"table="student">
<idname="sid"type="java.lang.Integer">
<columnname="sid"></column>
<generatorclass="native"></generator>
</id>
<propertyname="sname"type="java.lang.String">
<columnname="sname"length="40"></column>
</property>
<setname="teachers"
table="stu_tea_tab"
cascade="save-update"inverse="false"
>
<keycolumn="sid"></key>
<many-to-manyclass="com.test.beans.Teacher"column="tid"></many-to-many>
</set>
</class></hibernate-mapping>
hibernatesessionfactory.java
package com.test.hibernate;
import org.hibernate.HibernateException;
importorg.hibernate.Session;
import org.hibernate.cfg.Configuration;public class HibernateSessionFactory {
privatestaticStringCONFIG_FILE_LOCATION="/com/test/hibernate/hibernate.cfg.xml";
privatestaticfinalThreadLocal<Session>threadLocal=newThreadLocal<Session>();
privatestaticConfigurationconfiguration=newConfiguration();
privatestaticorg.hibernate.SessionFactorysessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;static {
try{
configuration.configure(configFile);
sessionFactory=configuration.buildSessionFactory();
}catch(Exceptione){
System.err
.println("%%%%ErrorCreatingSessionFactory%%%%");
e.printStackTrace();
}
}
privateHibernateSessionFactory(){
}
publicstaticSessiongetSession()throwsHibernateException{
Session session = (Session) threadLocal.get();if (session == null || !session.isOpen()) {
if(sessionFactory==null){
rebuildSessionFactory();
}
session=(sessionFactory!=null)?sessionFactory.openSession()
:null;
threadLocal.set(session);
}return session; }
public static void rebuildSessionFactory() {
try{
configuration.configure(configFile);
sessionFactory=configuration.buildSessionFactory();
}catch(Exceptione){
System.err
.println("%%%%ErrorCreatingSessionFactory%%%%");
e.printStackTrace();
}
}publicstaticvoidcloseSession()throwsHibernateException{
Sessionsession=(Session)threadLocal.get();
threadLocal.set(null);if (session != null) {
session.close();
}
}
publicstaticorg.hibernate.SessionFactorygetSessionFactory(){
returnsessionFactory;
}
publicstaticvoidsetConfigFile(StringconfigFile){
HibernateSessionFactory.configFile=configFile;
sessionFactory=null;
}public static Configuration getConfiguration() {
returnconfiguration;
}}
studentdao.java
package com.test.daos;
import org.hibernate.Session;import org.hibernate.Transaction;
import com.test.beans.Student;import com.test.hibernate.HibernateSessionFactory;
public class StudentDao
{
publicvoidaddStudent(Studentstudent)
{
Sessionsession=HibernateSessionFactory.getSession();
Transactiontr=session.beginTransaction();
session.save(student);
tr.commit();
HibernateSessionFactory.closeSession();
}
}测试类:
package com.test.test;
import com.test.beans.Student;
importcom.test.beans.Teacher;
importcom.test.daos.StudentDao;
import com.test.daos.TeacherDao;public class Test{
publicstaticvoidmain(Stringargs[])
{Student stu1 = new Student();
stu1.setSname("stu1");
Studentstu2=newStudent();
stu2.setSname("stu2");
Teachertea1=newTeacher();
tea1.setTname("tea1");
Teachertea2=newTeacher();
tea2.setTname("tea2");
stu1.getTeachers().add(tea1);
stu1.getTeachers().add(tea2);
stu2.getTeachers().add(tea1);
stu2.getTeachers().add(tea2);
StudentDaostudentDao=newStudentDao();
studentDao.addStudent(stu1);
studentDao.addStudent(stu2);
}}
说明:在这里我们采用 学生 握有主动权去选择老师。
我个人觉得才用中间表的形式实现多对多比较好,降低了表和表之间的耦合度。
一点拙见。呵呵