hibernate 关联关系

来源:互联网 发布:c语言求素数代码 编辑:程序博客网 时间:2024/05/16 12:59

save the transient instance before flushing

具体错误为在one-to-many中,对many进行save时,由于没有加入one的外建,导致错误。具体解决方法:(1)、在one的hbm文件中 invest=true,如果你非要影响多的一方(invest=false),那就要用级联保存了,但同时注意一个问题,级联保存可能会引起字段不能为NULL的异常,解决方法可以将字段设计成可以为空,还有就是先保存,但业务应用是否允许就只有自己知道了(一般来说是不允许的)。(2)、在many保存前务必要求one的存在

 

hibernate级联保存,当对象id不是0时,会执行update操作,只有为0时,才执行insert


这样Customer和Order双向关联中,Hibernate探测到持久化对象Customer和Order的状态发生变化时,仅按照Order对象状态的变化来同步更新数据库.为了程序健壮,在建立两个对象的双向关联时,应同时修改两端对象的相应属性,如:
customer.getOrders().add(order);
order.setCustomer(customer);
解除关联时:
customer.getOrders().remove(order);
order.setCustomer(null);

 


在映射一对多的双向关联时,应该设置“one”的inverse = true
或者可以直接理解为<set>的属性inverse都要设置成"true"
如:
<hibernate-mapping>
  <class table="T_Orgnization" name="com.cjkgf.oa.model.Orgnization">
    <id access="field" name="id">
      <generator class="native"/>
    </id>
    <property name="name"/>
    <property name="sn" />
    <property name="description" />
   
    <many-to-one column="pid"  name="parent"/>
  
    <!-- 这个是"one"-->
    <set access="field" name="children" inverse="true">
      <key column="pid"/>
      <one-to-many class="com.cjkgf.oa.model.Orgnization"/>
    < t>
   
  </class>
</hibernate-mapping>


如果没有设置inverse="true"
Hibernate: insert into T_Orgnization (name, sn, description, pid) values (?, ?, ?, ?)
Hibernate: insert into T_Orgnization (name, sn, description, pid) values (?, ?, ?, ?)
Hibernate: insert into T_Orgnization (name, sn, description, pid) values (?, ?, ?, ?)
Hibernate: insert into T_Orgnization (name, sn, description, pid) values (?, ?, ?, ?)
Hibernate: update T_Orgnization set pid=? where id=?
Hibernate: update T_Orgnization set pid=? where id=?
Hibernate: update T_Orgnization set pid=? where id=?

 

设置inverse="true"
Hibernate: insert into T_Orgnization (name, sn, description, pid) values (?, ?, ?, ?)
Hibernate: insert into T_Orgnization (name, sn, description, pid) values (?, ?, ?, ?)
Hibernate: insert into T_Orgnization (name, sn, description, pid) values (?, ?, ?, ?)
Hibernate: insert into T_Orgnization (name, sn, description, pid) values (?, ?, ?, ?)

由此可见,如果inverse="true",Hibernate不在执行“update T_Orgnization...”语句

 


总结:
1、在映射一对多的双向关联关系时,应该在“one”方把inverse属性设为"true"
2、“inverse”为反转意思,这表关联关系发生反转,只能有“many”关联到“one”,即关联关系由“many”方维护
        所以建立两个对象的双向关联时应该同时修改关联两端的对象,否则不能保存对象的关联关系
如:
        org5.setChildren(set);       
        org6.setParent(org5);
        org7.setParent(org5);
        org8.setParent(org5);
       
3、当设置inverse="true"时,仅仅修改“one”方属性时,不会影响关联关系
   当不设置inverse="true"时,仅仅修改“one”方属性时,会影响关联关系

原创粉丝点击