zoukankan      html  css  js  c++  java
  • Hibernate区分不同对象的方法

    1.关系数据库按主键区分不同记录。

    create table CUSTOMERS (ID int promary key not null, NAME varchar(15));  
     
    insert into CUSTOMERS values(1, 'Tom');  
     
    insert into CUSTOMERS values(3, 'Tom');  
    2.Java语言按内存地址区别不同的对象。

    Customer c1 = new Customer("Tom");  
     
    Customer c2 = new Customer("Tome");  
     
    Customer c3 = c1;  
     
    // c1 == c3 结果为true 
     
    // c1 == c2 结果为false 
    3.Hibernate用对象标识符(OID)来区分不同对象。

    Customer c1 = (Customer)session.load(Customer.class, new Long(1));  
     
    Customer c2 = (Customer)session.load(Customer.class, new Long(1));  
     
    Customer c3 = (Customer)session.load(Customer.class, new Long(3));  
     
    // c1 == c2 结果为true  
     
    // c1 == c3 结果为false  
    以上程序中,三次调用了Session的load()方法,分别加载OID为1或3的Customer对象。以下是Hibernate三次加载Customer对象的流程。

    (1)第一次加载OID为1的Customer对象时,先从数据库的CUSTOMERS表中查询ID为1的记录,再创建相应的Customer实例,把它保存在Session缓存中,最后把这个对象的引用赋值给变量c1。

    (2)第二次加载OID为1的Customer对象时,直接把缓存中OID为1的Customer对象的引用赋值给c2,因为c1和c2引用同一个Customer对象。

    (3)当加载OID为3的Customer对象时,由于在缓存中不存在这样的对象,所以必须再次到数据库中查询OID为3的记录,再创建相应的Customer实例,把它保存存在Session缓存中,最后把这个对象的引用赋值给变量c3。

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    提取RDLC reporting相关dll的方式,打包客户端时需要用
    VS2012程序打包部署详解
    快速打包你的应用程序——Inno Setup
    "RDLC"报表-参数传递及主从报表
    如何在多个页中显示行标题和列标题 (Reporting Services)
    编译cocos2d-x 4.0版本
    2080Ti评测结果
    (转)u3d设计模式
    java基础知识(一)
    Java8新特性学习(一)--lambda表达式
  • 原文地址:https://www.cnblogs.com/jamesf/p/4751684.html
Copyright © 2011-2022 走看看