Hibernate Session的saveOrUpdate()方法

saveOrUpdate()方法同时包含了save()与update()方法的功能,如果传入的参数是临时对象,就调用save()方法;如果传入的参数是游离对象,就调用update()方法;如果传入的参数是持久化对象,那就直接返回。那么,saveOrUpdate()方法如何判断一个对象处于临时状态还是游离状态呢?如果满足以下情况之一,Hibernate就把它作为临时对象。

  • Java对象的OID取值为null。
  • Java对象具有version属性并且取值为null。
  • 在映射文件中为<id>元素设置了unsaved-value属性,并且IOD取值与unsaved-value属性值匹配。
  • 在映射文件中为version属性设置了unsaved-value属性,并且version属性取值与unsaved-value属性值匹配。
  • 自定义了Hibernate的Interceptor实现类,并且Interceptor的isUnsaved()方法返回Boolean.TRUE。

    在以下程序中,customer起初为游离对象,anotherCustomer起初为临时对象,session2的saveOrUpdate()方法分别将它们变为持久化对象:

        // 此处省略session1持久化Customer对象的代码

        ......

        Session session2 = sessionFactory.openSession();

        Transaction tx2 = session2.beginTransaction();

        Customer anotherCustomer = new Customer();

        anotherCustomer.setName("Tom");

       session2.saveOrUpdate(customer); // 使customer游离对象被session2关联

        session2.saveOrUpdate(anotherCustomer); // 使anotherCustomer临时对象被session2关联

        tx2.commit();

        session2.close();

    如果Customer类的id属性为java.lang.Long类型,它的默认值为null,那么session2很容易就判断出customer对象为游离对象,而anotherCustomer对象为临时对象。因此session2对customer对象执行update操作,对anotherCutomer对象执行insert操作。

    如果Customer类的id属性为long类型,它的默认值为0,此时需要显示设置<id>元素的unsaved-value属性,它的默认值为null:

        <id name="id" column="ID" unsaved-value="0">

            <genarator class="Custoer"/>

        </id>

    这样,如果Customer对象的id取值为0,Hibernate就会把它作为临时对象。

      

   --转自:http://blog.sina.com.cn/s/blog_530bf5d20100bynj.html

转载于:https://www.cnblogs.com/xc1366/archive/2011/09/11/2173613.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值