The complex usage of hibernate hibernatecallback
Hibernatetemplate also provides a more flexible way to manipulate databases in such a way that hibernate can be used in a fully operational manner. Hibernatetemplate's flexible access is done in the following two ways:
Q Object Execute (hibernatecallback action)
Q List Execute (hibernatecallback action)
Both methods require an instance of Hibernatecallback, and the Hibernatecallback instance can be used in any valid hibernate data access. Through Hibernatecallback, program developers can use hibernate to access the database in a flexible way, addressing the shortcomings of the spring package's lack of flexibility after hibernate. Hibernatecallback is an interface with only one method Doinhibernate (org.hibernate.Session session), and the method has only one parameter session.
Typically, the program uses an anonymous inner class that implements Hibernatecallback to get hibernatecallback instances, and the method Doinhibernate method body is the persisted operation that spring performs. The specific code is as follows:
public class Persondaoimpl implements Persondao
{
Private instance variable save Sessionfactory
Private Sessionfactory sessionfactory;
Setter method required for Dependency injection
public void Setsessionfactory (Sessionfactory sessionfactory) {
This.sessionfactory = sessionfactory;
}
/**
*
* Find all the person instances that match the name by name
*
* @param name
* matches the name of the person
*
* @return Match all person collections for this appointment
*
*/
Public List findpersonsbyname (final String name) {
Creating an Hibernatetemplate instance
Hibernatetemplate hibernatetemplate =new hibernatetemplate (this.sessionfactory);
Returns the result of the execute of hibernatetemplate
Return (List) Hibernatetemplate.execute (
Create an anonymous inner class
New Hibernatecallback () {
Public Object Doinhibernate (session session) throws hibernateexception{
Use the method of the conditional query to return
List result = Session.createcriteria (Person.class)
. Add (Restrictions.like ("name", name+ "%"). List ();
return result;
}
});
}
}
Note: The session can be accessed within the method Doinhibernate method, which is a session instance bound to the thread. The persistence layer operation within this method is identical to the persistence layer operation when spring is not used. This guarantees that access to hibernate can still be used for complex persistent layer accesses.
Usage of hibernatecallback in spring (GO)