Callback Functions in Hibernatetemplate: You can see that all operational implementations of the database in the Hibernatetemplate class are using callback functions
Hibernatetemplate callback function source code:
Public <T> T Execute (hibernatecallback<t> action) throws DataAccessException {
Return Doexecute (action, false);
}
Public <T> T executewithnativesession (hibernatecallback<t> action) {
Return Doexecute (action, true);
}
Analysis: Callback Letter Understanding: Call the Doexecute method in execute or executewithnativesession and pass the action as a parameter, and invoke the method in action in the Doexecute method
Parameter hibernatecallback<t> is an interface with only one doinhibernate (Session session) method, which can be implemented by creating an anonymous inner class in the form of doinhibernate ( Session session) Implement the specific logic in this method
The Doexecute method calls the Doinhibernate (Session session) method in the function Hibernatecallback, which is used to get a session and pass it into the Doinhibernate method Return Action.doinhibernate (Sessiontoexpose) is returned, and the return value from the Doinhibernate method in the class you implement is returned
Method The difference between execute executewithnativesession:
The Execute method uses the session proxy executewithnativesession to use the native session
Public interface Hibernatecallback<t> {
T Doinhibernate (Session session) throws Hibernateexception;
}
Protected <T> T Doexecute (hibernatecallback<t> action, Boolean enforcenativesession) throws DataAccessException {
Assert.notnull (Action, "Callback object must not is null");
Session session = NULL;
Boolean isnew = false;
try {
Session = Getsessionfactory (). Getcurrentsession ();
}
catch (Hibernateexception ex) {
Logger.debug ("Could not retrieve Pre-bound Hibernate session", ex);
}
if (session = = null) {
Session = Getsessionfactory (). Opensession ();
Session.setflushmode (flushmode.manual);
IsNew = true;
}
try {
Enablefilters (session);
Session Sessiontoexpose =
(Enforcenativesession | | isexposenativesession () session:createsessionproxy (session));
Return Action.doinhibernate (Sessiontoexpose);
}
catch (Hibernateexception ex) {
Throw Sessionfactoryutils.converthibernateaccessexception (ex);
}
catch (RuntimeException ex) {
Callback code threw application exception ...
Throw ex;
}
finally {
if (isnew) {
Sessionfactoryutils.closesession (session);
}
else {
Disablefilters (session);
}
}
}
Callback functions in the Hibernatetemplate