hyljava

Hibernate中用逆转工程实现多对多关系映射


history中的c_id与s_id分别是外键。
在hibernate中用myeclicpse逆转工程实现的多对多


将 CourseDAO 中的save方法 改成:
 public void save(Course transientInstance) {
  log.debug("saving Course instance");
  Session session=null;
  Transaction tx=null;
  try {
   session=getSession();
   tx=session.beginTransaction();
   
   
   session.save(transientInstance);
   tx.commit();
   log.debug("save successful");
  } catch (RuntimeException re) {
   log.error("save failed", re);
   if(tx!=null){
    tx.rollback();
   }
   throw re;
  }
 }
将 Student DAO 中的save方法 改成:

public void save(Student transientInstance) {
  log.debug("saving Student instance");
  Session session=null;
  Transaction tx=null;
  try {
   session=getSession();
   tx=session.beginTransaction();
   
   session.save(transientInstance);
   log.debug("save successful");
  } catch (RuntimeException re) {
   log.error("save failed", re);
   if(tx!=null){
    tx.rollback();
   }
   throw re;
  }
 }
将 HistoryDAO 中的save方法 改成:

public void save(History transientInstance) {
  log.debug("saving History instance");
  Session session=null;
  Transaction tx=null;
  try {
   session=getSession();
   tx=session.beginTransaction();
   session.save(transientInstance);
   tx.commit();
   log.debug("save successful");
  } catch (RuntimeException re) {
   log.error("save failed", re);
   if(tx!=null){
    tx.rollback();
   }
   throw re;
  }
 }
测试类如下:

public class Test {

public static void main(String[] args) {
    Course course=new Course();
    CourseDAO cdao=new CourseDAO();
  
  Student stu=new Student();
  StudentDAO sdao=new StudentDAO();
    
  History his=new History();
  HistoryId hid=new HistoryId();
  HistoryDAO hdao=new HistoryDAO();
  
  
    course.setCName("c++");
    course.setCTer("张三");
  
  stu.setSName("张同学");
  stu.setSAge(22);
  
  hid.setCourse(course);
  hid.setStudent(stu);
   
   his.setId(hid);
      cdao.save(course);
   sdao.save(stu);
   hdao.save(his);
  }

}


posted on 2012-05-13 18:04 何云隆 阅读(238) 评论(0)  编辑  收藏 所属分类: Hibernate


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


网站导航: