(转)Hibernate的一级缓存

http://blog.csdn.net/yerenyuan_pku/article/details/70148567

Hibernate的一级缓存

Hibernate的一级缓存就是指Session缓存。通过查看Session接口的实现类——SessionImpl.java的源码可发现有如下两个类: 

  • actionQueue它是一个行动队列,它主要记录crud操作的相关信息。
  • persistenceContext它是持久化上下文,它其实才是真正的缓存。

在Session中定义了一系列的集合来存储数据,它们构成了Session的缓存。只要Session没有关闭,它就会一直存在。当我们通过Hibernate中的Session提供的一些API例如save()、get()、update()等进行操作时,就会将持久化对象保存到Session中,当下一次再去查询缓存中具有的对象(通过OID值来判断),就不会去从数据库中查询了,而是直接从缓存中获取。Hibernate的一级缓存存在的目的就是为了减少对数据库的访问。 
当然了,在Hibernate中还有一个二级缓存,它是SessionFactory级别缓存,我也不明白,所以在这儿,我就不做介绍了。

演示一级缓存的存在

现在我举例来演示一级缓存的存在。首先我们肯定要搭建好Hibernate的开发环境,读过我前面文章的童鞋,应该可以快速搭建好的,在此不做过多赘述。 
在cn.itheima.test包下新建一个单元测试类——HibernateTest.java,我们首先编写如下方法来测试一级缓存的存在:

public class HibernateTest {

    // 测试一级缓存
    @Test
    public void test3() {
        // 1.得到session
        Session session = HibernateUtils.openSession();
        session.beginTransaction();

        Customer customer = session.get(Customer.class, 1); // 查询id=1的Customer对象,如果查询到,会将Customer对象存储到一级缓存中
        Customer customer2 = session.get(Customer.class, 1); // 会从一级缓存中查询,而不会向数据库再发送sql语句查询

        // 2.事务提交,并关闭session
        session.getTransaction().commit();
        session.close();
    }

}

首次查询id为1的Customer对象时,Hibernate会向MySQL数据库发送如下SQL语句:

select
    customer0_.id as id1_0_0_,
    customer0_.name as name2_0_0_,
    customer0_.address as address3_0_0_,
    customer0_.sex as sex4_0_0_
from
    hibernateTest.t_customer customer0_
where
    customer0_.id=?

而第二次查询时,并没有向MySQL数据库发送select语句。这是因为首次查询id为1的Customer对象时,如果查询到,就会将Customer对象存储到一级缓存中,第二次查询时,会从一级缓存中查询,而不会向数据库再发送select语句查询。

持久化对象具有自动更新数据库的能力

现在我举例来演示持久化对象具有自动更新数据库的能力。在HibernateTest单元测试类中编写如下方法:

public class HibernateTest {

    // 持久化对象具有自动更新数据库的能力
    @Test
    public void test4() {
        // 1.得到session
        Session session = HibernateUtils.openSession();
        session.beginTransaction();
        Customer customer = session.get(Customer.class, 1); // 查询id=1的Customer对象,如果查询到,会将Customer对象存到一级缓存中
        customer.setName("Tom"); // 操作持久化对象来修改属性
        // 2.事务提交,并关闭session
        session.getTransaction().commit();
        session.close();
    }

}

测试以上test4方法,将发现数据库t_customer表中,id为1的那条记录的name字段变为Tom,这足以说明持久化对象具有自动更新数据库的能力了。但是为什么持久化对象具有自动更新数据库的能力呢?原因涉及到一个概念——快照,快照就是当前一级缓存里面对象的散装数据(对象的属性,如name、id……)。当执行完以下这句代码:

Customer customer = session.get(Customer.class, 1);

就会向一级缓存中存储数据,一级缓存其底层使用了一个Map集合来存储,Map的key存储的是一级缓存对象,而value存储的是快照。通过在这句代码上打个断点,然后以debug的方式运行,Watch一下session会看得更加清楚,如下: 

接着执行以下这句代码:

customer.setName("Tom");

执行完毕会修改一级缓存中的数据,如下: 

当事务提交,session关闭,向数据库发送请求时,会判断一级缓存中数据是否与快照区一致,如果不一样,就会发送update语句。

一级缓存常用API

一级缓存特点:

  1. 当我们通过session的save、update、saveOrUpdate方法进行操作时,如果一级缓存中没有对象,那么会从数据库中查询到这些对象,并存储到一级缓存中。
  2. 当我们通过session的load、get、Query的list等方法进行操作时,会先判断一级缓存中是否存在数据,如果没有才会从数据库获取,并且将查询的数据存储到一级缓存中。
  3. 当调用session的close方法时,session缓存将清空。

一级缓存常用的API:

  1. clear():清空一级缓存。
  2. evict():清空一级缓存中指定的某个对象。
  3. refresh():重新查询数据库,用数据库中的信息来更新一级缓存与快照区。

现在我举例来演示一级缓存常用的API。在HibernateTest单元测试类中编写如下方法:

public class HibernateTest {

    // 测试一级缓存操作常用的API
    @Test
    public void test5() {
        // 1.得到session
        Session session = HibernateUtils.openSession();
        session.beginTransaction();

        // 操作
        List<Customer> list = session.createQuery("from Customer").list(); // 这个操作会存储数据到一级缓存
        session.clear(); // 清空一级缓存
        Customer c = session.get(Customer.class, 1); // 会先从session的一级缓存中获取,如果不存在,才会从数据库里面获取

        session.evict(c); // 从一级缓存中删除一个指定的对象
        Customer cc = session.get(Customer.class, 1);

        cc.setName("kkkk");
        session.refresh(cc); // refresh方法的作用是:它会用数据库里面的数据来同步我们的一级缓存以及快照区,
                             // 这样的话,再操作cc时,就不会发送update语句。
                             // refresh方法:重新查询数据库,用数据库中的信息来更新一级缓存与快照区

        // 2.事务提交,并关闭session
        session.getTransaction().commit();
        session.close();
    }

}

可通过debug方式运行,这样会看得更清楚。在此不做过多赘述,读者自行操作。

Hibernate中常用API-Session的补充

讲完Hibernate持久化对象的三种状态和一级缓存之后,我就可以继续深入一点的讲解Session类中的以下方法了。

update

udpate操作主要是针对于脱管对象而言的,因为持久化对象具有自动更新数据库的能力。如果我们直接操作的对象是一个脱管对象,执行update会出现什么情况?如下:

public class HibernateTest {

    // session的update操作
    @Test
    public void test6() {
        // 1.得到session
        Session session = HibernateUtils.openSession();
        session.beginTransaction();

        // 执行update来操作一个脱管对象
        Customer c = new Customer();
        c.setAddress("天门");
        c.setName("赵六");
        c.setId(1); // 注意:我这里是为了模拟,所以手动给其赋值ID,正常的实际开发中是不建议这么做的

        session.update(c); // 当执行update时,会将c放入到session的一级缓存

        // 2.事务提交,并关闭session
        session.getTransaction().commit();
        session.close();
    }

}

运行以上test6方法,可以发现数据库t_customer表中id为1的记录已经更新了。得出结论:update操作时,如果操作的对象是一个脱管对象,则可以操作,并且它会将脱管对象转换成持久对象再操作。但是这里依然会引发两个问题:

  1. 如果在session中出现相同的oid的两个对象,会产生如下异常:

    org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session : [cn.itheima.domain.Customer#1]
        at org.hibernate.engine.internal.StatefulPersistenceContext.checkUniqueness(StatefulPersistenceContext.java:648)
        at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:284)
        at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:227)
        at org.hibernate.event.internal.DefaultUpdateEventListener.performSaveOrUpdate(DefaultUpdateEventListener.java:38)
        at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
        at org.hibernate.internal.SessionImpl.fireUpdate(SessionImpl.java:703)
        at org.hibernate.internal.SessionImpl.update(SessionImpl.java:695)
        at org.hibernate.internal.SessionImpl.update(SessionImpl.java:690)
        at cn.itheima.test.HibernateTest.test6(HibernateTest.java:127)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
        at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
        at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

    示例代码为:

    public class HibernateTest {
    
        // session的update操作
        @Test
        public void test6() {
            // 1.得到session
            Session session = HibernateUtils.openSession();
            session.beginTransaction();
    
            // 得到id=1的Customer对象
            Customer cc = session.get(Customer.class, 1); // session的一级缓存中存在了一个OID为1的Customer对象
    
            // 执行update来操作一个脱管对象
            Customer c = new Customer();
            c.setAddress("天门");
            c.setName("赵六");
            c.setId(1); // 注意:我这里是为了模拟,所以手动给其赋值ID,正常的实际开发中是不建议这么做的
    
            session.update(c); // 当执行update时,会将c放入到session的一级缓存
    
            // 2.事务提交,并关闭session
            session.getTransaction().commit();
            session.close();
        }
    
    }

    运行以上方法就会报上面的那个异常。 
    结论:session的一级缓存里面是不能出现两个相同OID的对象的

  2. 脱管对象的oid如果在数据表中不存在,会报异常如下:
    org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
        at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:67)
        at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:54)
        at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:46)
        at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3071)
        at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2950)
        at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3330)
        at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:145)
        at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:560)
        at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:434)
        at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
        at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
        at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1282)
        at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:465)
        at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:2963)
        at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2339)
        at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:485)
        at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:147)
        at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
        at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:231)
        at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:65)
        at cn.itheima.test.HibernateTest.test6(HibernateTest.java:130)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
        at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
        at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

    示例代码为:

    public class HibernateTest {
    
        // session的update操作
        @Test
        public void test6() {
            // 1.得到session
            Session session = HibernateUtils.openSession();
            session.beginTransaction();
    
            // 执行update来操作一个脱管对象
            Customer c = new Customer();
            c.setAddress("天门");
            c.setName("赵六");
            c.setId(11); // 注意:我这里是为了模拟,所以手动给其赋值ID,正常的实际开发中是不建议这么做的
    
            session.update(c); // 当执行update时,会将c放入到session的一级缓存
    
            // 2.事务提交,并关闭session
            session.getTransaction().commit();
            session.close();
        }
    
    }

    运行以上方法就会报上面的那个异常。

所以,在实际操作中,除非一些特殊情况(但要保证OID一定要有),建议通过持久化对象来直接修改其操作。

saveOrUpdate

如果对象是一个瞬时对象,则执行save操作;如果对象是一个脱管对象(脱管对象在数据库中可能会存在),则执行update操作;如果对象是一个持久化对象,则不需要去处理它,而是直接返回。

delete

删除一个脱管对象时,首先要与session关联,然后再删除;如果是删除一个持久化对象,则直接删除。 
注意:如果执行delete操作,那么先删除一级缓存,再删除数据库表中的数据

时间: 2024-08-25 10:55:22

(转)Hibernate的一级缓存的相关文章

Hibernate的一级缓存

Hibernate的一级缓存其实就是Session内置的一个Map,用来缓存它操作过的实体对象,对象的主关键字ID是Map的key,实体对 象就是对应的值.所以,一级缓存是以实体对象为单位进行存储的,访问时也是以实体为单位的(直接访问属性是不能使用缓存的),并且要求使用主关键字ID来 进行访问. 一级缓存是由Session提供的,所以它只存在于Session的生命周期中,当程序调用 save(),update(),saveorupdate()等方法以及调用查询接口list,filter,iter

Hibernate学习笔记(三) — Hibernate 的一级缓存意义

什么是缓存? 缓存说白了,就是应用程序向数据库要数据,然后把一些数据,临时的放在了内存的区域中,第二次再要数据的时候,直接从内存中拿即可. 缓存需要解决的事情: 1.能把数据放入缓存 2.能把数据从缓存中取出来 3.如果缓存中的数据发生变化,需要把数据同步到数据库中 4.把数据库中的数据同步到缓存中 5.hits命中率低的对象应该及时从缓存中移走 分布式缓存: 为什么会有分布式缓存? 应用程序运行在服务器上,并发访问时,服务器压力过大,分布式缓存就是来分担服务器压力的. 分布式缓存之间的数据是同

hibernate(二)一级缓存和三种状态解析

序言 前一篇文章知道了什么是hibernate,并且创建了第一个hibernate工程,今天就来先谈谈hibernate的一级缓存和它的三种状态,先要对着两个有一个深刻的了解,才能对后面我要讲解的一对多,一对一.多对多这种映射关系更好的理 --WH 一.一级缓存和快照 什么是一级缓存呢? 很简单,每次hibernate跟数据库打交道时,都是通过session来对要操作的对象取得关联,然后在进行操作,那么具体的过程是什么样的呢? 1.首先session将一个对象加入自己的管理范围内,其实也就是把该

hibernate学习(四)hibernate的一级缓存&amp;快照

缓存:提高效率 硬件的 CPU缓存   硬盘缓存   内存 软件的  io流缓存 hibernate  的一级缓存   也是为了操作数据库的效率. 证明一级缓存在  : Person p=session .get(Person.class, 1); Person p1=session.get(Person.class,2); Person  p2=session.get(Person.class,3); System.out.println(p=p1); 控制台输出为: select   * 

Hibernate中一级缓存和二级缓存

缓存是介于应用程序和物理数据源之间,其作用是为了降低应用程序对物理数据源访问的频次,从而提高了应用的运行性能.缓存内的数据是对物理数据源中的数据的复制,应用程序在运行时从缓存读写数据,在特定的时刻或事件会同步缓存和物理数据源的数据. 缓存的介质一般是内存,所以读写速度很快.但如果缓存中存放的数据量非常大时,也会用硬盘作为缓存介质.缓存的实现不仅仅要考虑存储的介质,还要考虑到管理缓存的并发访问和缓存数据的生命周期. Hibernate的缓存包括Session的缓存和SessionFactory的缓

Hibernate之一级缓存

时间:2017-1-20 14:48 --一级缓存 1.什么是缓存    缓存是将数据库.硬盘上的文件中的数据,放入到缓存中.    缓存就是内存中的一块空间,当再次使用数据时,可以直接从内存中获得. 2.缓存的优点    提高程序运行的效率,缓存技术是Hibernate的一个优化手段. 3.Hibernate分为两个级别的缓存:    1)一级缓存:        Session级别的缓存,一级缓存与Session生命周期一致,是自带的,不可卸载.        一级缓存缓存的是对象的引用. 

Hibernate中一级缓存概念以及flush与clear的区别

Hibernate采用缓存机制提高数据查询效率.缓存分为一级缓存和二级缓存,一级缓存在Session中存在,二级缓存需要手动配置. 在一级缓存中,如果数据保存到数据库中后,而session又没有关闭的话,那么这些数据会放到缓存中,再次发出查询请求,Hibernate首先检查缓存中是否有该数据,如果找到该数据,那么就不会向数据库发起查询请求而是直接将缓存中的数据取出.请看下面的例子: public class Main { public static void main(String[] args

Hibernate中一级缓存和二级缓存使用详解

一.一级缓存二级缓存的概念解释 (1)一级缓存就是Session级别的缓存,一个Session做了一个查询操作,它会把这个操作的结果放在一级缓存中,如果短时间内这个 session(一定要同一个session)又做了同一个操作,那么hibernate直接从一级缓存中拿,而不会再去连数据库,取数据: (2)二级缓存就是SessionFactory级别的缓存,顾名思义,就是查询的时候会把查询结果缓存到二级缓存中,如果同一个sessionFactory 创建的某个session执行了相同的操作,hib

Hibernate一级缓存和二级缓存深度比较

1.什么是缓存 缓存是介于应用程序和物理数据源之间,其作用是为了降低应用程序对物理数据源访问的频次,从而提高了应用的运行性能.缓存内的数据是对物理数据源中的数据的复制,应用程序在运行时从缓存读写数据,在特定的时刻或事件会同步缓存和物理数据源的数据. 缓存的介质一般是内存,所以读写速度很快.但如果缓存中存放的数据量非常大时,也会用硬盘作为缓存介质.缓存的实现不仅仅要考虑存储的介质,还要考虑到管理缓存的并发访问和缓存数据的生命周期. Hibernate的一级缓存是内置的,不能被卸载. Hiberna