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。

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

  • 相关阅读:
    pycharm中Terminal中运行用例
    python pandas模块简单使用(读取excel为例)
    pytest框架,使用print在控制台输入
    CentOS7配置python3教程
    linux 添加与修改用户归属组
    python 连接oracle基础环境配置方法
    robot framework 接口post请求需要加headers
    unittest中的parameterized参数化
    json格式
    Django_URL
  • 原文地址:https://www.cnblogs.com/jamesf/p/4751684.html
Copyright © 2011-2022 走看看