hibernate一级缓存_Hibernate缓存–一级缓存

hibernate一级缓存

Welcome to Hibernate Caching – First Level Cache Example Tutorial. Recently we looked into Hibernate architecture, hibernate mapping and how to use HQL for firing SQL queries in object oriented way. Today we will look into one of the important aspects of Hibernate – Hibernate Cache.

欢迎使用Hibernate Caching –一级缓存示例教程。 最近,我们研究了Hibernate体系结构hibernate映射以及如何使用HQL以面向对象的方式触发SQL查询。 今天,我们将研究Hibernate的重要方面之一-Hibernate Cache

Hibernate缓存 (Hibernate Caching)

Hibernate Cache can be very useful in gaining fast application performance if used correctly. The idea behind cache is to reduce the number of database queries, hence reducing the throughput time of the application.

如果正确使用Hibernate Cache,在获得快速应用程序性能方面将非常有用。 缓存背后的想法是减少数据库查询的数量,从而减少应用程序的吞吐时间。

Hibernate comes with different types of Cache:

Hibernate带有不同类型的缓存:

  1. First Level Cache: Hibernate first level cache is associated with the Session object. Hibernate first level cache is enabled by default and there is no way to disable it. However hibernate provides methods through which we can delete selected objects from the cache or clear the cache completely.

    Any object cached in a session will not be visible to other sessions and when the session is closed, all the cached objects will also be lost.

    一级缓存 :Hibernate一级缓存与Session对象相关联。 默认情况下,Hibernate一级缓存处于启用状态,无法禁用它。 但是,hibernate提供了一些方法,通过这些方法,我们可以从缓存中删除选定的对象或完全清除缓存。

    会话中缓存的任何对象对其他会话都不可见,并且在关闭会话时,所有缓存的对象也将丢失。

  2. Second Level Cache: Hibernate Second Level cache is disabled by default but we can enable it through configuration. Currently EHCache and Infinispan provides implementation for Hibernate Second level cache and we can use them. We will look into this in the next tutorial for hibernate caching.

    二级缓存 :默认情况下,Hibernate二级缓存是禁用的,但我们可以通过配置启用它。 目前,EHCache和Infinispan为Hibernate Second level缓存提供了实现,我们可以使用它们。 我们将在下一个教程中研究Hibernate缓存。
  3. Query Cache: Hibernate can also cache result set of a query. Hibernate Query Cache doesn’t cache the state of the actual entities in the cache; it caches only identifier values and results of value type. So it should always be used in conjunction with the second-level cache.

    查询缓存 :Hibernate也可以缓存查询结果集。 Hibernate Query Cache不会在缓存中缓存实际实体的状态。 它仅缓存标识符值和值类型的结果。 因此,应始终将其与二级缓存结合使用。

Hibernate缓存–一级缓存示例 (Hibernate Caching – First Level Cache Example)

For my hibernate first level cache example program, I am using same configuration as in HQL Example, you can check that out and configure the tables and populate it with dummy data.

对于我的Hibernate一级缓存示例程序,我使用的配置与HQL Example中的配置相同,您可以检出并配置表,并用伪数据填充表。

Let’s first look into the program, it’s output and then we will go through some of the important points related to Hibernate First Level Cache.

首先,让我们看一下程序的输出,然后我们将介绍与Hibernate First Level Cache相关的一些重要信息。

HibernateCacheExample.java

HibernateCacheExample.java

package com.journaldev.hibernate.main;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.journaldev.hibernate.model.Employee;
import com.journaldev.hibernate.util.HibernateUtil;

public class HibernateCacheExample {

	public static void main(String[] args) throws InterruptedException {
		
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.getCurrentSession();
		Transaction tx = session.beginTransaction();
		
		//Get employee with id=1
		Employee emp = (Employee) session.load(Employee.class, new Long(1));
		printData(emp,1);
		
		//waiting for sometime to change the data in backend
		Thread.sleep(10000);
		
		//Fetch same data again, check logs that no query fired
		Employee emp1 = (Employee) session.load(Employee.class, new Long(1));
		printData(emp1,2);
		
		//Create new session
		Session newSession = sessionFactory.openSession();
		//Get employee with id=1, notice the logs for query
		Employee emp2 = (Employee) newSession.load(Employee.class, new Long(1));
		printData(emp2,3);
		
		//START: evict example to remove specific object from hibernate first level cache
		//Get employee with id=2, first time hence query in logs
		Employee emp3 = (Employee) session.load(Employee.class, new Long(2));
		printData(emp3,4);
		
		//evict the employee object with id=1
		session.evict(emp);
		System.out.println("Session Contains Employee with id=1?"+session.contains(emp));

		//since object is removed from first level cache, you will see query in logs
		Employee emp4 = (Employee) session.load(Employee.class, new Long(1));
		printData(emp4,5);
		
		//this object is still present, so you won't see query in logs
		Employee emp5 = (Employee) session.load(Employee.class, new Long(2));
		printData(emp5,6);
		//END: evict example
		
		//START: clear example to remove everything from first level cache
		session.clear();
		Employee emp6 = (Employee) session.load(Employee.class, new Long(1));
		printData(emp6,7);
		Employee emp7 = (Employee) session.load(Employee.class, new Long(2));
		printData(emp7,8);
		
		System.out.println("Session Contains Employee with id=2?"+session.contains(emp7));
		
		tx.commit();
		sessionFactory.close();
	}

	private static void printData(Employee emp, int count) {
		System.out.println(count+":: Name="+emp.getName()+", Zipcode="+emp.getAddress().getZipcode());
	}

}

When we run above example, the output contains a lot of hibernate related information. But we are mostly interested in our code specific output and the queries fired by hibernate to load the data. The output snippet looks like below.

当我们在上面的示例中运行时,输出包含许多与Hibernate相关的信息。 但是我们对特定于代码的输出以及由hibernate触发以加载数据的查询最感兴趣。 输出代码段如下所示。

Hibernate Configuration loaded
Hibernate serviceRegistry created
Hibernate: select employee0_.emp_id as emp_id1_1_0_, employee0_.emp_name as emp_name2_1_0_, employee0_.emp_salary as emp_sala3_1_0_, address1_.emp_id as emp_id1_0_1_, address1_.address_line1 as address_2_0_1_, address1_.city as city3_0_1_, address1_.zipcode as zipcode4_0_1_ from EMPLOYEE employee0_ left outer join ADDRESS address1_ on employee0_.emp_id=address1_.emp_id where employee0_.emp_id=?
1:: Name=Pankaj, Zipcode=95129
2:: Name=Pankaj, Zipcode=95129
Hibernate: select employee0_.emp_id as emp_id1_1_0_, employee0_.emp_name as emp_name2_1_0_, employee0_.emp_salary as emp_sala3_1_0_, address1_.emp_id as emp_id1_0_1_, address1_.address_line1 as address_2_0_1_, address1_.city as city3_0_1_, address1_.zipcode as zipcode4_0_1_ from EMPLOYEE employee0_ left outer join ADDRESS address1_ on employee0_.emp_id=address1_.emp_id where employee0_.emp_id=?
3:: Name=PankajK, Zipcode=95129
Hibernate: select employee0_.emp_id as emp_id1_1_0_, employee0_.emp_name as emp_name2_1_0_, employee0_.emp_salary as emp_sala3_1_0_, address1_.emp_id as emp_id1_0_1_, address1_.address_line1 as address_2_0_1_, address1_.city as city3_0_1_, address1_.zipcode as zipcode4_0_1_ from EMPLOYEE employee0_ left outer join ADDRESS address1_ on employee0_.emp_id=address1_.emp_id where employee0_.emp_id=?
4:: Name=David, Zipcode=95051
Session Contains Employee with id=1?false
Hibernate: select employee0_.emp_id as emp_id1_1_0_, employee0_.emp_name as emp_name2_1_0_, employee0_.emp_salary as emp_sala3_1_0_, address1_.emp_id as emp_id1_0_1_, address1_.address_line1 as address_2_0_1_, address1_.city as city3_0_1_, address1_.zipcode as zipcode4_0_1_ from EMPLOYEE employee0_ left outer join ADDRESS address1_ on employee0_.emp_id=address1_.emp_id where employee0_.emp_id=?
5:: Name=Pankaj, Zipcode=95129
6:: Name=David, Zipcode=95051
Hibernate: select employee0_.emp_id as emp_id1_1_0_, employee0_.emp_name as emp_name2_1_0_, employee0_.emp_salary as emp_sala3_1_0_, address1_.emp_id as emp_id1_0_1_, address1_.address_line1 as address_2_0_1_, address1_.city as city3_0_1_, address1_.zipcode as zipcode4_0_1_ from EMPLOYEE employee0_ left outer join ADDRESS address1_ on employee0_.emp_id=address1_.emp_id where employee0_.emp_id=?
7:: Name=Pankaj, Zipcode=95129
Hibernate: select employee0_.emp_id as emp_id1_1_0_, employee0_.emp_name as emp_name2_1_0_, employee0_.emp_salary as emp_sala3_1_0_, address1_.emp_id as emp_id1_0_1_, address1_.address_line1 as address_2_0_1_, address1_.city as city3_0_1_, address1_.zipcode as zipcode4_0_1_ from EMPLOYEE employee0_ left outer join ADDRESS address1_ on employee0_.emp_id=address1_.emp_id where employee0_.emp_id=?
8:: Name=David, Zipcode=95051
Session Contains Employee with id=2?true

Hibernate重要点中的一级缓存 (First Level Cache in Hibernate Important Points)

Important Points about First level cache in Hibernate that can be derived from above program are:

可以从上述程序派生的有关Hibernate中一级缓存的要点是:

  1. Hibernate First Level cache is enabled by default, there are no configurations needed for this.

    默认情况下,Hibernate First Level缓存是启用的,不需要任何配置。
  2. Hibernate first level cache is session specific, that’s why when we are getting the same data in same session there is no query fired whereas in other session query is fired to load the data.

    Hibernate一级缓存是特定于会话的,这就是为什么当我们在同一会话中获取相同的数据时,不会触发查询,而在其他会话中,会触发查询来加载数据。
  3. Hibernate first level cache can have old values, as you can see above that I have put my program to sleep for 10 seconds and in that time I updated the value (name from Pankaj to PankajK) in database but it didn’t get reflected in the same session. But in other session, we got the updated value.

    Hibernate一级缓存可能具有旧值,如上所示,我已使程序进入睡眠状态10秒钟,在那段时间内我更新了数据库中的值(名称从Pankaj改为PankajK),但未在其中反映出来。同一会话。 但是在其他会话中,我们获得了更新的值。
  4. We can use session evict() method to remove a single object from the hibernate first level cache.

    我们可以使用session evict()方法从Hibernate一级缓存中删除单个对象。
  5. We can use session clear() method to clear the cache i.e delete all the objects from the cache.

    我们可以使用session clear()方法清除缓存,即从缓存中删除所有对象。
  6. We can use session contains() method to check if an object is present in the hibernate cache or not, if the object is found in cache, it returns true or else it returns false.

    我们可以使用session contains()方法检查Hibernate缓存中是否存在对象,如果在缓存中找到该对象,则返回true,否则返回false。
  7. Since hibernate cache all the objects into session first level cache, while running bulk queries or batch updates it’s necessary to clear the cache at certain intervals to avoid memory issues.

    由于Hibernate将所有对象缓存到会话一级缓存中,因此在运行批量查询或批处理更新时,必须按一定的时间间隔清除缓存以避免内存问题。

That’s all for hibernate caching and first level cache example, in future posts we will look into Hibernate Second Level Cache – EHCache implementation.

这就是Hibernate缓存和一级缓存示例的全部内容,在以后的文章中,我们将研究Hibernate二级缓存– EHCache实现。

翻译自: https://www.journaldev.com/2969/hibernate-caching-first-level-cache

hibernate一级缓存

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值