日期:2014-05-18  浏览次数:20622 次

hibernate级联保存.
我有两张表 Apple ,Pear 
Apple 表结构(三个字段) id aName ,address
Pear 表结构(4个字段) pid ,pName,pk ,sid(外键)
Apple主表,Pear从表
建立表关系 alter table Pear add constraint f_king foreign key (sid) references Apple (id) on update cascade on delete cascade 
级联删除,级联更新 ,然后hibernate生成配置文件 一对多关系,

Java code

      public static void main(String args[]){
      Configuration config = new Configuration().configure();
      SessionFactory  factory = config.buildSessionFactory();
      Session  sess= factory.openSession();
          Set  st = new HashSet();
          Transaction tx = sess.beginTransaction();
      try{
      Apple  app = new Apple();Pear   pea = new Pear();
      app.setAname("水精灵");app.setAddress("水晶龙");
      pea.setPname("苹果");  pea.setPk("李子"); pea.setApple(app);
      st.add(pea);
      app.setPears(st);
      sess.save(app);
      tx.commit();
      }catch(Exception ex){
          if(tx!=null){
              tx.rollback();
          }
          ex.printStackTrace();
      }finally{
          sess.close();
      }
   }


生成后的 Apple 的属性
private Integer id;private Set pears = new HashSet(0);private String aname;private String address;
生成后的 Pear 属性 private Integer pid;private Apple apple;private String pname;private String pk;

1个问题:
1.事务提交后,只有主表Apple保存了数据,从表没有添加?..难道就不能一次性保存主表和从表的数据吗?一定要sess.Save(apple(主表对象)) sess.Save(pear(从表对象)) 分别保存一次,hibernate执行两次数据库操作?
当然sess.Save(apple(主表对象)) sess.Save(pear(从表对象)) 后分别保存了数据...


------解决方案--------------------
你在Apple 的配置文件中的set属性上加上cascade="save"试试看情况如何。
------解决方案--------------------
cascade="all"

解释一下:
all所有情况下均进行关联操作。
none所有情况下均不进行关联操作。这是默认值。
save-update在执行save/update/saveOrUpdate时进行关联操作。
delete在执行delete时进行关联操作。