Hi!
I setup hibernate2.1 with tomcat as described in the online reference documentation. Now I'll try to play with the cats and got some troubles :-(
I wrote and compiled my cat class, my cat-xml and the hibernate.xml exists - so far so good.
Now I tried to write the util-class.
the line:
Code:
private static SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
couldn't compiled, cause configure() throws an exception that "must be caught or declared to be thrown".
I'm not a java-expert, but I think in a var-declaration I can't define a try/catch - statement?!
And a
Code:
....configure().buildSessionFactory() throws Exception;
isn't allowed too.
What is the right solution? My way is writing:
Code:
private static SessionFactory sessionFactory;
But (!) the sessionFactory must initialised - ok, we have a constructor:
Code:
public Util() throws Exception {
sessionFactory = new Configuration().configure().buildSessionFactory;
}
Next problem is when calling in a JSP the line
Code:
Session session = Util.currentSession();
Tomcat crashed with a NullPointerException in currentSession(): sessionFactory was not initialised!
M I right, that the call "class.method()" runs without passing the constructor-method???
I changeed the JSP line into:
Code:
Util util = new Util();
Session session = util.currentSession();
ok, now the constructer-method is called, but I got an other error:
"Cannot inherit from final class"
This error is thrown by "Configuration().configure()".
Arrgh! :-( Beating my head on the wall ... Where is _my_ mistake!??! I would be very happy for every hint!!
tol
Here my source code:
Code:
public class Util
{
private static SessionFactory sessionFactory;
public static final ThreadLocal mysession = new ThreadLocal();
public Util() throws Exception {
sessionFactory = new Configuration().configure().buildSessionFactory() ;
}
public Session currentSession() throws HibernateException {
Session s = (Session) mysession.get();
// Open a new Session, if this Thread has none yet
if (s == null) {
s = sessionFactory.openSession();
mysession.set(s);
}
return s;
}
public void closeSession() throws HibernateException {
Session s = (Session) mysession.get();
mysession.set(null);
if (s != null) s.close();
}
} // end class util
** JSP **
Code:
<%
Util util = new Util();
Session mysession = util.currentSession();
// Session mysession = Util.currentSession();
//The rest of the example is remarked while testing
%>