• Hibernate session.saveOrUpdate()方法


    saveOrUpdate()方法同时包含了save()与update()方法的功能,
    如果传入的参数是临时对象,就调用save()方法;
    如果传入的参数是游离对象,就调用update()方法;
    如果传入的参数是持久化对象,那就直接返回。

    那么,saveOrUpdate()方法如何判断一个对象处于临时状态还是游离状态呢?如果满足以下情况之一,Hibernate就把它作为临时对象。
    Java对象的OID取值为null。
    Java对象具有version属性并且取值为null。
    在映射文件中为元素设置了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就会把它作为临时对象
    你以为躲起来就找不到你了吗?没有用的!象你这样出色的男人,无论在什么地方,都像漆黑中的萤火虫一样,那样的鲜明,那样的出众。你那忧郁的眼神,稀嘘的胡喳子,神乎其神的刀法,和那杯Dry Martine,都深深地迷住了我!
  • 相关阅读:
    java 正则 二次转义
    HDU1789 Doing Homework again 【贪心】
    扣丁学堂笔记第22天多媒体播放
    [Python]BeautifulSoup—HTML解析包
    Android高级控件(三)——&#160;使用Google ZXing实现二维码的扫描和生成相关功能体系
    Business Process and SAP ERP
    HTML基础知识总结一
    控制器View是怎样创建的?
    cocos2d-x 3.0 场景切换特效汇总
    LeetCode 3Sum
  • 原文地址:https://www.cnblogs.com/wjjFJ/p/5241165.html
Copyright © 2020-2023  润新知