-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 21 posts ]  Go to page 1, 2  Next
Author Message
 Post subject: First step troubles
PostPosted: Sun Dec 07, 2003 12:16 pm 
Newbie

Joined: Sun Dec 07, 2003 11:27 am
Posts: 11
Location: Berlin
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

%>

_________________
recordcaster.de - independent internet radio berlin


Top
 Profile  
 
 Post subject:
PostPosted: Sun Dec 07, 2003 2:12 pm 
Hibernate Team
Hibernate Team

Joined: Mon Aug 25, 2003 9:11 pm
Posts: 4592
Location: Switzerland
I'm sorry, the code in the quickstart was just wrong. I wrote it without realizing that Exceptions can not be thrown in static initialization. So here is a working class:

Code:

import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;

public class HibernateUtil {

   private static SessionFactory sessionFactory;
   public static final ThreadLocal session = new ThreadLocal();

   public static Session currentSession()
         throws HibernateException {

      // Initialize SessionFactory first time
      if (sessionFactory == null) {
         synchronized (sessionFactory) {
            sessionFactory = new Configuration().configure().buildSessionFactory();
         }
      }

      Session s = (Session) session.get();

      // Open a new Session, if this Thread has none yet
      if (s == null) {
         s = sessionFactory.openSession();
         session.set(s);
      }

      return s;
   }

   public static void closeSession()
         throws HibernateException {

      Session s = (Session) session.get();
      session.set(null);
      if (s != null) s.close();
   }

}


I just wanted to avoid the synchronisation, stupid me.

_________________
JAVA PERSISTENCE WITH HIBERNATE
http://jpwh.org
Get the book, training, and consulting for your Hibernate team.


Top
 Profile  
 
 Post subject:
PostPosted: Sun Dec 07, 2003 2:21 pm 
Hibernate Team
Hibernate Team

Joined: Mon Aug 25, 2003 9:11 pm
Posts: 4592
Location: Switzerland
By "working" I mean "it compiles". :)

It would be really great if you can test it, I just have no demo project around to test it quickly and I'm using other ways to manage SessionFactory/Session these days.

_________________
JAVA PERSISTENCE WITH HIBERNATE
http://jpwh.org
Get the book, training, and consulting for your Hibernate team.


Top
 Profile  
 
 Post subject:
PostPosted: Sun Dec 07, 2003 5:57 pm 
Newbie

Joined: Sun Dec 07, 2003 11:27 am
Posts: 11
Location: Berlin
Hey cool! Thanks for that quickie answer :-)

I tested the new sourcecode. A problem is at the follwing lines


Code:
// Initialize SessionFactory first time
if (sessionFactory == null) {
   synchronized (sessionFactory) {
            sessionFactory = new Configuration().configure().buildSessionFactory();
   }
}


When you set the synchronized-block, sessionFactory is at this time null ... and tomcat didn't like it ;-)

I'm not familiar with the synchronized-mechanism, so I experienced with "this" or "getClass()" but the compiler says "non-static method cannot be referenced from a static context". So I choose a private Boolean Var.

Code:
private static Boolean blocked = new Boolean(false);

synchronized (blocked) {
...
}


Didn't know if it's the best, but now that part works - ... next step hang up again. The line

Code:
sessionFactory = new Configuration().configure().buildSessionFactory();


makes some trouble and tomcat tells: Cannot inherit from final class. Some error as before - what a final class??

I assume it has something to do with that configure()-method ...

Some idea??

tol

_________________
recordcaster.de - independent internet radio berlin


Top
 Profile  
 
 Post subject:
PostPosted: Sun Dec 07, 2003 6:32 pm 
Hibernate Team
Hibernate Team

Joined: Mon Aug 25, 2003 9:11 pm
Posts: 4592
Location: Switzerland
Grrr, I hate synchronization in Java. Still waiting for anyone to write a good summary about the options. You can just skip the synchronized block and simply create the SessionFactory if its null, but that might result in a race condition. I actually don't know how its all connected to statics and optimizer and whatnot.

I had a static init() method in such a class in my other projects, calling it only once on application startup and in that method, initializing the SessionFactory.

I can't help you with the other error, I really don't know why its complaining about a final class. I think I have to rework that example and really test my code before posting it public :)

_________________
JAVA PERSISTENCE WITH HIBERNATE
http://jpwh.org
Get the book, training, and consulting for your Hibernate team.


Top
 Profile  
 
 Post subject:
PostPosted: Mon Dec 08, 2003 3:37 am 
Hibernate Team
Hibernate Team

Joined: Tue Aug 26, 2003 7:19 pm
Posts: 2364
Location: Brisbane, Australia
I have done a lot of threading work in C++ and Java. The problem was that each java class carries a monitor lock with it. Because the object was null there was no monitor lock so it complained. You should have synchronized the currentSession method, or used an external object to lock on as shown. If taking that approach I tend to just use Object, eg, static Object lock = new Object();


Top
 Profile  
 
 Post subject:
PostPosted: Mon Dec 08, 2003 7:01 am 
Newbie

Joined: Sun Dec 07, 2003 11:27 am
Posts: 11
Location: Berlin
Ok, thanks :-) I'l try the sync a bit later. Now I think, the main problem is the "inherit from final class" message. But perhaps it is better I open a new topic ...

tol

_________________
recordcaster.de - independent internet radio berlin


Top
 Profile  
 
 Post subject:
PostPosted: Mon Dec 08, 2003 7:28 am 
Expert
Expert

Joined: Fri Nov 07, 2003 4:24 am
Posts: 315
Location: Cape Town, South Africa
Hi Christian, Tol

Here is a reworked code snippet from the tutorial that avoids synchronisation and compiles - you may want to update the docs:

Code:
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;

public class HibernateUtil {
   
   private static final SessionFactory sessionFactory;
   
   static {
      try {
         sessionFactory = new Configuration().configure().buildSessionFactory();
      } catch (HibernateException ex) {
         throw new RuntimeException("Exception building session factory: " + ex.getMessage(), ex);
      }
   }
   
   public static final ThreadLocal session = new ThreadLocal();
   
   public static Session currentSession() throws HibernateException {
      Session s = (Session) session.get();
      // Open a new Session, if this Thread has none yet
      if (s == null) {
         s = sessionFactory.openSession();
         session.set(s);
      }
      return s;
   }
   public static void closeSession() throws HibernateException {
      Session s = (Session) session.get();
      session.set(null);
      if (s != null)
         s.close();
   }
}


Top
 Profile  
 
 Post subject:
PostPosted: Mon Dec 08, 2003 8:01 am 
Hibernate Team
Hibernate Team

Joined: Mon Aug 25, 2003 9:11 pm
Posts: 4592
Location: Switzerland
Oh yes, static init block. Thanks!

_________________
JAVA PERSISTENCE WITH HIBERNATE
http://jpwh.org
Get the book, training, and consulting for your Hibernate team.


Top
 Profile  
 
 Post subject:
PostPosted: Mon Dec 08, 2003 8:05 am 
Newbie

Joined: Sun Dec 07, 2003 11:27 am
Posts: 11
Location: Berlin
Hey thanks drj :-) hmm .... I really don't like it to let you down, but I still got this error "Cannot inherit from final class" again. Could it be that this error is created from a completely other module/class???

tol

_________________
recordcaster.de - independent internet radio berlin


Top
 Profile  
 
 Post subject:
PostPosted: Mon Dec 08, 2003 8:11 am 
Expert
Expert

Joined: Fri Nov 07, 2003 4:24 am
Posts: 315
Location: Cape Town, South Africa
Post the code of the classes that you are getting the error from. Sounds like you are trying to extend a final class. i.e.
Code:
public final Class Foo {}

public class Bar extends Foo {}

Bar won't compile because Foo is marked as final. The example that I see in the documentation doesn't include such a class though...

Something weird is going on here but I suspect it's your environment. Please also specify which version of Hiberate, & JDK

Regards
Justin


Top
 Profile  
 
 Post subject:
PostPosted: Mon Dec 08, 2003 8:49 am 
Newbie

Joined: Sun Dec 07, 2003 11:27 am
Posts: 11
Location: Berlin
Hi Justin!

Here is my code:


HibernateUtil Class - exactly what you've posted

Code:
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;

public class HibernateUtil {
   
   private static final SessionFactory sessionFactory;
   
   static {
      try {
         sessionFactory = new Configuration().configure().buildSessionFactory();
      } catch (HibernateException ex) {
         throw new RuntimeException("Exception building session factory: " + ex.getMessage(), ex);
      }
   }
   
   public static final ThreadLocal mysession = new ThreadLocal();
   
   public static 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 static void closeSession() throws HibernateException {
      Session s = (Session) mysession.get();
      mysession.set(null);
      if (s != null)
         s.close();
   }
}


and my simple test jsp:

Code:
<%@page contentType="text/html"%>
<%@page import="HibernateUtil" %>
<%@page import="net.sf.hibernate.*" %>

<%
    Session mysession = HibernateUtil.currentSession();
    Transaction tx= mysession.beginTransaction();
    HibernateUtil.closeSession();
%>
<html>
<head><title>JSP Page</title></head>
<body>
</body>
</html>


that's all - a very simple test :-)
the compiler has nothing to reject, but tomcat throws a runtimerror:

Code:
javax.servlet.ServletException: Cannot inherit from final class
   at org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:497)
   at org.apache.jsp.test_jsp._jspService(test_jsp.java:63)
   at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:136)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
[...]


here an extract from the compiled servlet test_jsp.java:

Code:
try {
      _jspxFactory = JspFactory.getDefaultFactory();
      response.setContentType("text/html;charset=ISO-8859-1");
      pageContext = _jspxFactory.getPageContext(this, request, response,
                        null, true, 8192, true);
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\n");
      out.write("\n");
      out.write("\n\n");

    Session my1session = HibernateUtil.currentSession();
    Transaction tx= my1session.beginTransaction();
    HibernateUtil.closeSession();
      out.write("\n");
      out.write("<html>\n");
      out.write("<head>");
      out.write("<title>JSP Page");
      out.write("</title>");
      out.write("</head>\n");
      out.write("<body>\n\n\n\n\n");
      out.write("</body>\n");
      out.write("</html>\n");
    } catch (Throwable t) {
      out = _jspx_out;
      if (out != null && out.getBufferSize() != 0)
        out.clearBuffer();
      >>>>if (pageContext != null) pageContext.handlePageException(t);<<<<
    } finally {
      if (_jspxFactory != null) _jspxFactory.releasePageContext(pageContext);
    }


The marked >>>> line is lineno. 63 ...

any idea?

Tol

_________________
recordcaster.de - independent internet radio berlin


Top
 Profile  
 
 Post subject:
PostPosted: Mon Dec 08, 2003 9:01 am 
Newbie

Joined: Sun Dec 07, 2003 11:27 am
Posts: 11
Location: Berlin
... I forgot the versions:
- j2sdk1.4.2_01
- hibernate-2.1rc1
- Tomcat 4.1.12

Tol

_________________
recordcaster.de - independent internet radio berlin


Top
 Profile  
 
 Post subject:
PostPosted: Mon Dec 08, 2003 9:17 am 
Expert
Expert

Joined: Fri Nov 07, 2003 4:24 am
Posts: 315
Location: Cape Town, South Africa
Hi,

I successfully compiled and ran the class file (jsp --> servlet). My generated file is the same as yours.

I am using tomcat 4.1.29 / jdk 1.4.2_02 and Hibernate 2.0

I have seen this problem reported with old versions of dependent libraries (xerces and commons-beanutils are some likely culprits). If you can upgrade tomcat I would recommend a fresh install. Also check your tomcat logs (webapp/logs) - there may be a more descriptive error message in there.

Justin


Top
 Profile  
 
 Post subject:
PostPosted: Mon Dec 08, 2003 9:27 am 
Hibernate Team
Hibernate Team

Joined: Mon Aug 25, 2003 9:11 pm
Posts: 4592
Location: Switzerland
Some useful tips for Tomcat:

- If you found a version that works, never change it! New Tomcat versions usually have new bugs.

- Never mess with the global classpath in Toamcat, that is, never copy anything but your JDBC driver to common/lib or any other "global" library directory.

- Don't use Tomcat if you can use Jetty or Resin or whatever.

_________________
JAVA PERSISTENCE WITH HIBERNATE
http://jpwh.org
Get the book, training, and consulting for your Hibernate team.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 21 posts ]  Go to page 1, 2  Next

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.