免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2380 | 回复: 0
打印 上一主题 下一主题

hibernate级联插入实现多对多 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-11-27 11:14 |只看该作者 |倒序浏览

最近学习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 的配置文件:

  
   
   
  
  
   
  
  
   
   
  

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

  
   
   
  
  
   
  
  
   
   
  

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 threadLocal = new ThreadLocal();
    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 );
}
}
说明:在这里我们采用 学生 握有主动权去选择老师。
我个人觉得才用中间表的形式实现多对多比较好,降低了表和表之间的耦合度。
一点拙见。呵呵


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/50617/showart_2105262.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP