Java世界

学习笔记

常用链接

统计

积分与排名

天籁村

新华网

雅虎

最新评论

hibernate级联插入实现多对多

一个例子 实现多对多的 插入 采用中间表的形式 进行操作

代码如下:

teacher table


    create table `test`.`teacher`(
        `tid` int not null auto_increment,
       `tname` varchar(40),
        primary key (`tid`)
    );

    create unique index `PRIMARY` on `test`.`teacher`(`tid`);

studnt table


    create table `test`.`student`(
        `sid` int not null auto_increment,
       `sname` varchar(40),
        primary key (`sid`)
    );

    create unique index `PRIMARY` on `test`.`student`(`sid`);

stu_tea_tab table


    create table `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()
 {
 
  return tid;
 }

 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"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
 Mapping file autogenerated by MyEclipse Persistence Tools
-->

<hibernate-mapping>
 <class name="com.test.beans.Teacher" table="teacher">
  <id name="tid" type="java.lang.Integer">
   <column name="tid"></column>
   <generator class="native"></generator>
  </id>
  <property name="tname" type="java.lang.String">
   <column name="tname" length="40"></column>
  </property>
  <set name="students" table="stu_tea_tab" inverse="true" cascade="save-update">
   <key column="tid"></key>
   <many-to-many class="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
{
 private Integer sid;
 private String sname;
 private Set teachers = new HashSet();
 
 
 public String getSname()
 {
 
  return sname;
 }
 public void setSname(String sname)
 {
 
  this.sname = sname;
 }
 public Integer getSid()
 {
 
  return sid;
 }
 public void setSid(Integer sid)
 {
 
  this.sid = sid;
 }
 public Set getTeachers()
 {
 
  return teachers;
 }
 public void setTeachers(Set teachers)
 {
 
  this.teachers = teachers;
 }
 
 
}

student.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
 Mapping file autogenerated by MyEclipse Persistence Tools
-->

<hibernate-mapping>
 <class name="com.test.beans.Student" table="student" >
  <id name="sid" type="java.lang.Integer">
   <column name="sid"></column>
   <generator class="native"></generator>
  </id>
  <property name="sname" type="java.lang.String">
   <column name="sname" length="40"></column>
  </property>
  <set name="teachers"
    table="stu_tea_tab"
    cascade="save-update"

   inverse="false"
   >
   <key column="sid"></key>
   <many-to-many class="com.test.beans.Teacher" column="tid"></many-to-many>
  </set>
 </class>

</hibernate-mapping>

hibernatesessionfactory.java

package com.test.hibernate;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

public class HibernateSessionFactory {
    private static String CONFIG_FILE_LOCATION = "/com/test/hibernate/hibernate.cfg.xml";
 private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

 static {
     try {
   configuration.configure(configFile);
   sessionFactory = configuration.buildSessionFactory();
  } catch (Exception e) {
   System.err
     .println("%%%% Error Creating SessionFactory %%%%");
   e.printStackTrace();
  }
    }
    private HibernateSessionFactory() {
    }
 
    public static Session getSession() throws HibernateException {
        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 (Exception e) {
   System.err
     .println("%%%% Error Creating SessionFactory %%%%");
   e.printStackTrace();
  }
 }


    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

 
 public static org.hibernate.SessionFactory getSessionFactory() {
  return sessionFactory;
 }

 
 public static void setConfigFile(String configFile) {
  HibernateSessionFactory.configFile = configFile;
  sessionFactory = null;
 }

 public static Configuration getConfiguration() {
  return configuration;
 }

}

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
{
 public void addStudent(Student student)
 {
  Session session = HibernateSessionFactory.getSession ( );
  
  Transaction tr = session.beginTransaction ( );
  
  session.save ( student );
  

  tr.commit();
  HibernateSessionFactory.closeSession ( );
 }
}

测试类:

package com.test.test;

 

import com.test.beans.Student;
import com.test.beans.Teacher;
import com.test.daos.StudentDao;
import com.test.daos.TeacherDao;

public class Test
{


 public static void main(String args[])
 
 {

  Student stu1 = new Student();
  stu1.setSname ( "stu1" );
  Student stu2 = new Student();
  stu2.setSname ( "stu2" );
  
  Teacher tea1 = new Teacher();
  tea1.setTname ( "tea1" );
  
  Teacher tea2 = new Teacher();
  tea2.setTname ( "tea2" );
  
  stu1.getTeachers ( ).add ( tea1 );
  stu1.getTeachers ( ).add ( tea2 );
  
  stu2.getTeachers ( ).add ( tea1 );
  stu2.getTeachers ( ).add ( tea2 );
  
  StudentDao studentDao = new StudentDao();
  
  studentDao.addStudent ( stu1 ); 
  studentDao.addStudent ( stu2 ); 
 }

}

说明:在这里我们采用 学生 握有主动权去选择老师。

posted on 2010-12-20 15:29 Rabbit 阅读(1886) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: