Basic concepts of cache in Hibernate
I. Basic concepts of Cache
Simple case:
Session s = null;
Transaction tx = null;
Try {
S = HibernateUtil. getCurrentSession ();
Tx = s. beginTransaction ();
Student stu1 = (Student) s. get (Student. class, 2 );
System. out. println (stu1.getName ());
Student stu2 = (Student) s. get (Student. class, 2 );
System. out. println (stu2.getName ());
Tx. commit ();
} Catch (Exception e ){
If (tx! = Null ){
Tx. rollback ();
}
} Finally {
If (s! = Null & s. isOpen ()){
S. close ();
}
}
Query results:
Hibernate: select student0 _. id as id1_0 _, student0 _. name as name1_0 _, student0 _. dept_id as dept3_1_0 _ from Student student0 _ where student0 _. id =?
Daming
Daming
Only one query statement is executed for two queries, indicating that the second query is not performed.
Ii. Basic concepts of level-1 Cache
1. What operations will input data to the first-level cache?
Save, update, saveOrUpdate, load, get, list, iterate, lock
Save case:
// Add a student
Student student = new Student ();
Student. setName (Xiaodong );
S. save (student); // put it into the first-level cache
// Query immediately
Student stu2 = (Student) s. get (Student. class, student. getId (); // select
System. out. println (the name of the student you just joined is + stu2.getName ());
2. What operations will be performed to retrieve data from the first-level cache?
Get/load/list
Get/load will first be retrieved from the first-level cache, if not. different operations [get will immediately send a request to the database, and load will return a proxy object until the user actually uses the data, it will send a request to the database]
? Will the list retrieve data from the session cache?
Case:
// Query student 45
Student stu = (Student) s. get (Student. class, 45 );
System. out. println (||||||||||||||||||| );
String hql = from Student where id = 45;
Student stu2 = (Student) s. createQuery (hql). uniqueResult ();
System. out. println (stu2.getName ());
From the above case, I can see that query. list () query. uniueResut () will not take data from the first level! However, query. list or query. uniqueRestu () will put data to the first-level cache.
3. Lifecycle
The lifecycle of objects in the session-level cache. When the session is closed, it is automatically destroyed.
Iii. Level 2 Cache
1. Configuration required
Update
True
Org. hibernate. cache. OSCacheProvider
2. The second-level cache is handled by a third party. Common Hashtable, OSCache, and EHCache
3. Principle of second-level cache
First, you can search for the first-level cache. If the first-level cache does not exist, you can search for the second-level cache. When the second-level cache finds the object, it stores a copy of the object in the first-level cache, when this object is searched again, It is found in the first-level cache.
4. The second-level cache objects may be stored in the memory or disk.