Three major Java frameworks-three data persistence statuses and cache mechanisms in Hibernate, three major hibernate
Three statuses in Hibernate
Instantaneous status:The newly created object is not persistent by the Session, the data of this object does not exist in the cache, and the data corresponding to this object in the database is not in the instantaneous state.OID.
Persistent status:When the object passes the Session persistence operation, the data of this object in the cache is in the persistent state and the data of this object in the database is in the persistent state.OID.
Free Status:When the Session is closed, the cache does not contain the object data and the database contains the object data and the OID is in the Free State.
Note:OIDIn order to find the desired object in the system, we need to assign a unique representation for each object. In relational databases, we call it a keyword. In object terms, it is called an object identifier.
(Object identifier-OID). Generally, the OID is represented by one or more big integers internally, while in the application, a complete class is provided to obtain and operate other classes.
Hibernate data status chart:
Note that:
When the temporary state of an object changes to the persistent state. When the object is in the persistent state, it is always in the Session cache and any operations on it will be synchronized to the database when the transaction is committed. Therefore, it is meaningless to call the save () or update () method for a persistent object.
Student stu = new Strudnet (); stu. setCarId ("200234567"); stu. setId ("100"); // open the Session and start the transaction // persistently operate the session of the stu object. save (stu); stu. setCardId ("20076548"); // perform the persistent operation session on the stu object again. save (stu); // invalid session. update (stu); // invalid // submit the transaction and close the Session
Hibernate Cache Mechanism
What is cache?
The cache is between applications and physical data sources. It is used to reduce the frequency of applications accessing physical data sources and improve the running performance of applications. Data in the cache is the replication of data in the physical data source. during runtime, the application reads and writes data from the cache. Data in the cache and the physical data source will be synchronized at a specific time or event.
What are the benefits of caching?
The advantage of caching is that it reduces the number of database accesses, improves application performance, and reduces the time required to read and write data.
When is cache suitable?
Some unchanged data content is often used in programs. If you do not frequently modify it after checking it out from the database, you can consider using a cache. You can read it from the cache after reading it, instead of having to query the database every time. Because the hard disk speed is much slower than the memory speed. So as to improve the performance of the program, the emergence of cache will solve this problem
Cache in Hibernate
Cache in HibernateIncludingLevel 1 cache (Session cache),SessionFactory Cache)AndQuery Cache.
Level 1 cache (Session cache)
Because the lifecycle of a Session Object usually corresponds to a database transaction or an application transaction, its cache is the cache of the transaction scope. Session-level cache is required and cannot be detached. In Session-level cache, each instance of the persistence class has a unique OID.
When an application calls Session save (), update (), savaeOrUpdate (), get (), or load (), and the list (), iterate () or the filter () method. If no corresponding object exists in the Session cache, Hibernate adds the object to the first cache.
When cache is cleared, Hibernate synchronously updates the database based on the state changes of the objects in the cache.
Session provides two methods for applications to manage the cache: evict (Object obj): Clear the persistence Object specified by the parameter from the cache. Clear (): clears all persistent objects in the cache.
Public static void testOneLeveCache () {Session session = HibernateUtil. getSession (); // get the Persistent Object Dept d1 = (Dept) session. get (Dept. class, 10); // obtain the Persistent Object Dept d2 = (Dept) session again. get (Dept. class, 10); session. close ();}
The get () method of the Session gets the Dept object. By default, the Dept object is saved to the first-level cache (Session cache) when the second request is obtained, the corresponding object is queried from the first-level cache (the premise is that the Session cannot be cleared or closed; otherwise, the first-level cache is cleared or destroyed) if a corresponding object exists in the first-level cache, the query code is as follows:
Hibernate: select dept0_.DEPTNO as DEPTNO0_0_, dept0_.DNAME as DNAME0_0_, dept0_.LOC as LOC0_0_ from SCOTT.DEPT dept0_ where dept0_.DEPTNO=?
How do I clear the first-level cache?
Clear all caches through session. clear (); //
Session. evict (); // clear the specified Cache
Public static void testOneLeveCache () {Session session = HibernateUtil. getSession (); SessionFactory sf = HibernateUtil. getSessionFactory (); // get the Persistent Object Dept d1 = (Dept) session. get (Dept. class, 10); session. clear (); // clear all cache sessions. evict (d1); // clear the specified cache // obtain the Persistent Object Dept d2 = (Dept) session again. get (Dept. class, 10); session. close ();}
When session. evict (Object obj) is used, the specified Bean is deleted. Therefore, when you query the Bean that is deleted from the second-level cache, two SQL statements are executed.
When Session. clear () is used, two SQL statements are executed:
Hibernate: select dept0_.DEPTNO as DEPTNO0_0_, dept0_.DNAME as DNAME0_0_, dept0_.LOC as LOC0_0_ from SCOTT.DEPT dept0_ where dept0_.DEPTNO=?Hibernate: select dept0_.DEPTNO as DEPTNO0_0_, dept0_.DNAME as DNAME0_0_, dept0_.LOC as LOC0_0_ from SCOTT.DEPT dept0_ where dept0_.DEPTNO=?
SessionFactory Cache)
Because the life cycle of the SessionFactory object corresponds to the whole process of the application, The Hibernate second-level cache is a cache of process scope or cluster scope, which may cause concurrency problems, therefore, an appropriate concurrent access policy is required, which provides a transaction isolation level for cached data.
The save, update, saveOrupdate, load, get, list, query, and Criteria methods all fill the second-level cache.
Get, load, iterate get data from the second-level cache session. save (user)
If the user primary key is generated using "native", it is not placed in the second-level cache.
The second-level cache is optional and is a configurable plug-in. By default, SessionFactory does not enable this plug-in. Hibernate provides the org. hibernate. cache. CacheProvider interface, which acts as an adapter between the cache plug-in and Hibernate.
The general process of Hibernate's second-level cache policy is as follows:
1) When performing conditional queries, a select * from table_name where… is always issued .... (Select all fields) This SQL statement queries the database and obtains all data objects at a time.
2) put all the data objects obtained into the second-level cache by ID.
3) When Hibernate accesses the Data Object Based on the ID, it first looks up the data object from the Session level cache. If the Session level-2 cache is not found, it will be found from the level-2 cache, query the database and put the result into the cache by ID.
4) when data is deleted, updated, or added, the cache is also updated.
Hibernate's second-level cache policy is a cache policy for ID queries and does not work for conditional queries. Therefore, Hibernate provides a Query Cache for conditional queries ).
Configure the SessionFactory Cache):
Configure the following code in hibernate. cfg. xml:
<! -- Enable Level 2 cache --> <property name = "hibernate. cache. use_second_level_cache"> true </property> <! -- Specify the implementation class of the second-level cache for hibernate --> <property name = "hibernate. cache. provider_class"> org. hibernate. cache. EhCacheProvider </property>
Specify the classes that need to be placed in the second-level cache. objects that need to be used for a long time can be put into the second-level cache in two ways:
1. InConfigure in hibernate. cfg. xml
<Class-cache class = "entity. petInfo "usage =" read-only "/> // objects in the cache cannot be updated. <class-cache class =" entity. petInfo "usage =" read-write "/> // allows you to update objects in the cache.
2. Configure in the Bean. hbm File
<Hibernate-mapping> <class name = "com. bdqn. entity. dept "table =" DEPT "schema =" SCOTT "> <cache usage =" read-only "/> // put this class into the second-level cache <id name =" deptno "type = "java. lang. integer "> <column name =" DEPTNO "precision =" 2 "scale =" 0 "/> <generator class =" assigned "> </generator> </id> <property name = "dname" type = "java. lang. string "> <column name =" DNAME "length =" 14 "/> </property> </class>
In the ehcache. xml configuration file, you can set the maximum number of caches, whether the cache is permanently valid, and the time.
<defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" />
How to clear the second-level cache?
You need to use SessionFactory to manage the second-level cache code as follows:
SessionFactory. evict (Entity. class); // clear all EntitysessionFactory. evict (Entity. class, id); // clear the specified Entity, for example: // use SessionFacotry to manage the second-level cache SessionFactory = HibernateUtils. getSessionFactory (); // evict () clears the Student object with id 1 from the second-level cache. factory. evict (Student. class, 1); // evict () clears all secondary caches. factory. evict (Student. class );
What kind of data is suitable for storing in the second-level cache?
1) rarely modified data
2) not very important data, allowing occasional Concurrent Data
3) data that will not be accessed concurrently
4) constant data
Is it not suitable for storing data in the second-level cache?
1) frequently modified data
2) concurrent access data, such as financial data, is absolutely not allowed.
3) data shared with other applications.
Query Cache)
The query cache of hibernate is mainly used to cache the result set of common attributes, while only the id is cached for the result set of object objects.
When the first-level cache, second-level cache, and query cache are enabled, the query operations are as follows:
To query common attributes, the database is queried first in the query cache. If no, the database is queried. to query entities, the IDs are obtained first in the query cache. If yes, the object is retrieved from the cache (level 1/Level 2) based on the id. If the object cannot be obtained from the cache, the database is queried.
Enable query cache in the hibernate. cfg. xml configuration file
<! -- Whether to enable query cache; true: Enable query cache; false: Disable query cache --> <property name = "cache. use_query_cache"> true </property>
After enabling the query cache, you also need to enable the query cache in the program.
Public static void testQueryCache () {Session session = HibernateUtil. getSession (); String hql = "from Emp as e"; Query query = session. createQuery (hql); query. setCacheable (true); // enable query cache (second-level cache) List <Emp> empList = query. list (); session. close ();}
The query cache is based on the second-level cache mechanism. If you do not enable the second-level cache for query based on Bean attributes, the Code is as follows:
Session = HibernateUtils. getSession (); t = session. beginTransaction (); Query query = session. createQuery ("select s. name from Student s "); // enables the query cache query. setCacheable (true); List <String> names = query. list (); for (Iterator <String> it = names. iterator (); it. hasNext ();) {String name = it. next (); System. out. println (name);} System. out. println ("================================ "); query = session. createQuery ("select s. name from Student s "); // enables the query cache query. setCacheable (true); // No query statement is issued, because the query cache names = query is used here. list (); for (Iterator <String> it = names. iterator (); it. hasNext ();) {String name = it. next (); System. out. println (name);} t. commit ();