@Component public class Hibernatetemplate {private static final threadlocal<session> ThreadLocal = new Threadlo
Cal<session> ();
private static Org.hibernate.SessionFactory sessionfactory; @Resource (name= "sessionfactory")//Here the static method using annotations will be unusually public static void Setsessionfactory (Org.hibernate.SessionFactory
sessionfactory) {hibernatetemplate.sessionfactory = sessionfactory; }/** * Returns the ThreadLocal Session instance.
Lazy Initialize * The <code>SessionFactory</code> if needed. * * @return Session * @throws Hibernateexception */public static session getsession () throws Hiberna
Teexception {Session session = (session) Threadlocal.get ();
if (session = = NULL | |!session.isopen ()) {session = (sessionfactory! = null)? Sessionfactory.getcurrentsession ()
: null;
Threadlocal.set (session);
} return session; }/** * Close the single hibernate session inStance. * * @throws hibernateexception */public static void CloseSession () throws Hibernateexception {Ses
Sion Session = (session) Threadlocal.get ();
Threadlocal.set (NULL);
if (session! = NULL) {session.close (); }}/** * return session Factory * */public static org.hibernate.SessionFactory Getsessionfactory (
) {return sessionfactory; }
}
Using the annotation method to inject sessionfactory an exception occurs:
caused by:org.springframework.beans.factory.BeanCreationException:Error creating bean with Name ' hibernatetemplate ' Defined in class path resource [Applicationcontext.xml]: post-processing failed of bean type [class Com.util.HibernateTemp Late] failed; Nested exception is java.lang.IllegalStateException:
@Resource annotation is isn't supported on static methods
Workaround:
Remove the annotations and replace them with hibernatetemplate in the Applicationcontext.xml.
<bean id= "Hibernatetemplate" class= "Com.util.HibernateTemplate" >
<property name= "Sessionfactory" ref= "Sessionfactory" ></property>
</bean>
or change the Sessessionfactory method to non-static
You can then inject hibernatetemplate from Basedao using annotation methods
Private hibernatetemplate template;
Public hibernatetemplate gettemplate () {
return template;
}
@Resource (name= "hibernatetemplate")
public void SetTemplate (hibernatetemplate template) {
This.template = template;
}