Difference between gethibernatetemplate () and getsession (): hibernate Level 1 second Cache

Source: Internet
Author: User

In spring integrated hibernate, two operations are provided for Dao layer access.

 

(1)Protected final session getsession () throws dataaccessresourcefailureexception, illegalstateexception;

Spring API explanation:

 

Obtain a hibernate session, either from the current transaction or a new one. The latter is only allowed if the "allowcreate" setting of this bean 'shibernatetemplate is "true ".

Note that this is not meant to be invoked from hibernatetemplate code but rather just in plain hibernate code.Either rely on a thread-bound session or use it in combination with releasesession (Org. hibernate. session ).

In general, it is recommended to use hibernatetemplate, either with the provided convenience operations or with a custom hibernatecallback that provides you with a session to work on.Hibernatetemplate will care for all resource management and for proper exception conversion.

 

 

(2)Public final hibernatetemplate gethibernatetemplate ();

Spring API explanation:

Note: The returned hibernatetemplate is a shared instance.

 

 

Http://blog.csdn.net/fenixshadow/archive/2007/09/26/1802277.aspx:GethibernatetemplateManaged by spring, a session is always used to connect to the database. Each time getsession () is used, a new session is created to connect to the database, which is not managed by spring.

 

Post (1) http://blog.csdn.net/fenixshadow/archive/2007/09/26/1802277.aspx

Both spring and Hibernate are out of the box. I have a little bit of experience today. Share it with you.

When we spent a lot of effort to finally complete the environment, there was a problem:
How to access the database?

By inheriting hibernatedaosupport, we have two options:
Getsession (). createquery ("from users ");
Gethibernatetemplate (). Find ("from users );

Which one is used? Confused.

Gethibernatetemplate is recommended for finding information online. The reason is not clear.

So I did the following test:

Call getsession (). createquery ("from users"); gethibernatetemplate (). Find ("from users) cyclically );
1000 times
As a result, the getsession () package will soon fail to establish a connection. However, gethibernatetemplate cannot be used up.

Through the background observation, using getsession will leave a lot of SQL * Net message from client connections in the database. After the test is terminated, the connection is automatically released.
Gethibernatetemplate uses a connection from start to end.

Does getsession () Fail to automatically release the connection?

So I cyclically call getsession (). createquery ("from users"); gethibernatetemplate (). Find ("from users );
5 times
It is found that when the front-end program ends, the five connections of getsession are immediately released. If the connection is automatically released after the previous 1000 tests are terminated, it means that getsession () will automatically release the connection.

Conclusion:
1. Both getsession () and gethibernatetemplate can automatically release connections (of course, your configuration must be correct ), however, getsession in a thread will get many sessions (that is, many sessions and connections), which may cause the database connection to exceed the upper limit. Therefore, gethibernatetemplate is recommended.

2. If gethibernatetemplateis useless, you can use gethibernatetemplate.exe cute to use the hibernatecallback callback interface.

In addition, you can set the allowcreate value of hibernatetemplate to true and disable the session in finally. You can also pass true as a parameter to the super. getsession (...) method to get the session. This is also possible, that is, the trouble.
See:
Http://springframework.org/docs/api/org/springframework/orm/hibernate3/HibernateTemplate.html
Http://www.mxjava.com/blog/article.asp? Id = 246


Please give us some advice.


In addition, the hibernatedao code automatically generated by myeclipse is used. In version 4.1.1, The findbyid method automatically generated by myeclipse uses the getsession method to obtain the connection. However, in version 6.0, it has been modified to use the gethibernatetemplate method. 5.0 is not tested.

 

Post (2) http://jeoff.blog.51cto.com/186264/133434

 

 

When the hibernate configuration file is automatically generated, the getsession () method will be used in the DaO layer to operate database records, but he still has a method gethibernatetemplate (). What are the differences between the two methods? 1. to use the getsession () method, you only need to inherit sessionfactory, while the gethibernatetemplate () method must inherit hibernatedaosupport, including sessionfactory. This difference is not particularly important. The following differences are very important. 2. the getsession () method is not packaged by spring. Spring will give you the most primitive session, and you must call the corresponding close method after use, in addition, declarative transactions will not be managed accordingly. Once the connection is not closed in time, the connection pool connections will overflow. The gethibernatetemplate () method is encapsulated by spring, for example, add the corresponding declarative Transaction Management and spring manages the corresponding connections. In actual use, it is found that gethibernatetemplate () is much better than the getsession () method, but some methods are not provided in gethibernatetemplate (). In this case, we use the hibernatecallback callback method to manage the database. for example, the following code :/**
* Use hql statements for operations
* @ Param hql hsql query statement (use the callback function to access external variables, which must be final)
* @ Param offset start to obtain the subscript of the data
* @ Param length: number of data records read
* @ Return list result set
*/
Public list getlistforpage (final string hql, final int offset, final int length) {list = gethibernatetemplate(.exe cutefind (New hibernatecallback (){
Public object doinhibernate (session) throws hibernateexception, sqlexception {
Query query = session. createquery (hql );
Query. setfirstresult (offset );
Query. setmaxresults (length );
List list = query. List ();
Return list;
}
});
Return list;
} Complex hibernate usage: hibernatecallback

Hibernatetemplate also provides a more flexible way to operate databases. In this way, you can fully use the hibernate operation method. The flexible access method of hibernatetemplate is achieved through the following two methods:

Qobject execute (hibernatecallback action)

Qlist execute (hibernatecallback action)

Both methods require a hibernatecallback instance, which can be used in any valid hibernate data access. Through hibernatecallback, program developers can access the database in a flexible way using hibernate to solve the lack of flexibility after spring encapsulates hibernate. Hibernatecallback is an interface with only one method doinhibernate (Org. hibernate. Session session). This method has only one parameter session.

Generally, the program uses an anonymous internal class that implements hibernatecallback to obtain instances of hibernatecallback. The method body of doinhibernate is the persistent operation executed by spring. The Code is as follows:

Public class persondaoimpl implements persondao

{
// Private instance variable save sessionfactory
Private sessionfactory
Sessionfactory;
// The setter method required for dependency Injection
Public void
Setsessionfactory (sessionfactory ){
This. sessionfactory =
Sessionfactory;
}
/**
*
* Search for all the person instances matching the name by name
*

* @ Param name
* Matched person name
*
* @ Return
All person sets matching the appointment
*
*/
Public list findpersonsbyname (final string
Name ){
// Create a hibernatetemplate instance
Hibernatetemplate
= New hibernatetemplate (this. sessionfactory );
//
Returns the execute result of hibernatetemplate.
Return (list)
Hibernatetemplate.exe cute (
// Create an anonymous internal class
New
Hibernatecallback (){
Public object doinhibernate (session) throws
Hibernateexception {
// Return using the conditional Query Method
List result =
Session. createcriteria (person. Class)
. Add (restrictions. Like ("name ",
Name + "%"). List ();
Return result;

}
});
}
}

Note: You can access the session in the doinhibernate method. The session object is bound to the session instance of the thread. The operation on the persistent layer in this method is exactly the same as the operation on the persistent layer when spring is not used. This ensures that the hibernate access method can still be used for complex persistent layer access. Turn: hibernate Level 1 Cache

The first-level cache of Hibernate is provided by the session, so it only exists in the session lifecycle. When the program calls methods such as Save (), update (), saveorupdate, and when the query interface list, filter, or iterate is called, if no corresponding object exists in the session cache, Hibernate will add this object to the first-level cache. When the session is closed, the level-1 cache managed by this session will be cleared immediately.

Java code
  1. Note: The first-level cache of Hibernate is built into the session and cannot be uninstalled or configured.
Note: The first-level cache of Hibernate is built into the session and cannot be uninstalled or configured.

The primary cache uses the key-value map method. When the object is cached, the primary key ID of the object is the key of the map, and the object is the corresponding value. Therefore, a level-1 cache is stored in Entity objects and uses the keyword ID during access. Although hibernate uses automatic maintenance and does not provide any configuration functions for the level-1 cache, manual intervention can be performed on the management of the level-1 cache through the methods provided in the session.

 

Difference between get and Load

When you use the get method to obtain a persistent object, first check whether the object exists in the session cache (level-1 cache). If yes, the object is obtained. If not, the database is accessed, if no data is found in the database, null is returned.
The load method also obtains data, but the difference is that the load method already assumes that the data exists in the Database. If the data cannot be found in the database, an org. hibernate. objectnotfoundexception exception.
The load method obtains the object. The load method first searches for the object in the session cache. If the object cannot be found, it searches for the sessionfactory cache (second-level cache). If the object cannot be found, it accesses the database. It is worth noting that the load method assumes that the database must have this data, so the agent is used to delay loading the object. Only when the property of this object (non-primary key attribute) is used in the program, hibernate will enter the process of obtaining objects in the load method. Therefore, if this record does not exist in the database, an exception is thrown when the program accesses this object attribute, rather than when the object is created.

The second-level cache previously refers to the cache used by Hibernate and ehcache. spring3.1 provides support for ehcache. The second-level cache granularity of Hibernate is too small, and configuration is troublesome and is gradually replaced.

The first-level cache of Hibernate is provided by the session, so it only exists in the session lifecycle. When the program calls methods such as Save (), update (), saveorupdate, and when the query interface list, filter, or iterate is called, if no corresponding object exists in the session cache, Hibernate will add this object to the first-level cache. When the session is closed, the level-1 cache managed by this session will be cleared immediately.

Java code
  1. Note: The first-level cache of Hibernate is built into the session and cannot be uninstalled or configured.
Note: The first-level cache of Hibernate is built into the session and cannot be uninstalled or configured.

The primary cache uses the key-value map method. When the object is cached, the primary key ID of the object is the key of the map, and the object is the corresponding value. Therefore, a level-1 cache is stored in Entity objects and uses the keyword ID during access. Although hibernate uses automatic maintenance and does not provide any configuration functions for the level-1 cache, manual intervention can be performed on the management of the level-1 cache through the methods provided in the session.

 

Difference between get and Load

When you use the get method to obtain a persistent object, first check whether the object exists in the session cache (level-1 cache). If yes, the object is obtained. If not, the database is accessed, if no data is found in the database, null is returned.
The load method also obtains data, but the difference is that the load method already assumes that the data exists in the Database. If the data cannot be found in the database, an org. hibernate. objectnotfoundexception exception.
The load method obtains the object. The load method first searches for the object in the session cache. If the object cannot be found, it searches for the sessionfactory cache (second-level cache). If the object cannot be found, it accesses the database. It is worth noting that the load method assumes that the database must have this data, so the agent is used to delay loading the object. Only when the property of this object (non-primary key attribute) is used in the program, hibernate will enter the process of obtaining objects in the load method. Therefore, if this record does not exist in the database, an exception is thrown when the program accesses this object attribute, rather than when the object is created.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.