7

so I'm trying to get my Java Application to connect to SQL Server 2012 through the Microsoft JDBC Driver 4.0 for SQL Server, and everything seems to be going well but hibernate just keeps coming back with NullExceptions and won't execute anything within the try/catch (hence the NullException), I have absolutely no idea why. Here is the pastebin from netbeans console (e.getMessage()) running hibernate (for the purposes of this question, I am using an example table called prime_table).

In the pastebin log, you'll notice ...

Feb 11, 2013 5:21:04 PM org.hibernate.cfg.Configuration doConfigure INFO: Configured SessionFactory: null

any ideas on why this is occuring? (I'm not sure, but it may be relevant to the overall stack trace).

Other logs (During JSP build)

All logs will be available up until Mid/Late March 2013

Resources, I've been reading

Pre Configured Netbeans Project Setup commandline: tree /f

netbeans
(source: iforce.co.nz)

Hibernate.cfg.xml (Added "hibernate.cache.provider_class" as suggested by Hari)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>
    <property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
    <property name="hibernate.connection.url">jdbc:sqlserver://Michael-PC:1433;databaseName=PrimeDB</property>
    <property name="hibernate.connection.username">sa</property>
    <property name="hibernate.connection.password">online12</property>
    <property name="hibernate.connection.pool_size">10</property>
    <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <!-- Data Mappings -->
    <mapping resource="prime.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

Prime

public class Prime {

    private long prime;

    public void setPrime(long nPrime){
        this.prime = nPrime;
    }

    public long getPrime(){
        return this.prime;
    }

}

prime.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="nz.co.xyleap.db.Prime" table="prime_table">
    <id name="prime" type="long" column="prime" />
  </class>
</hibernate-mapping>

Prime Table

CREATE TABLE prime_table (
    [prime] bigint PRIMARY KEY NOT NULL,
)

Session function or FirstExample.java

public class FirstExample {

    public static void main(String[] args) {
        FirstExample ex = new FirstExample();
        ex.session();
    }

    public void session() {
        Session session = null;
        try {
            // This step will read hibernate.cfg.xml and prepare hibernate for use
            SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
            session = sessionFactory.openSession();
            session.beginTransaction();
            //Create new instance of Contact and set values in it by reading them from form object
            System.out.println("inserting record 13");
            Prime p = new Prime();
            p.setPrime(13);
            session.save(p);
            System.out.println("Done");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            // Actual contact insertion will happen at this step
            session.flush();
            session.close();
        }
    }

}

As far as I know everything should be correct, and I should be able to insert records from Java Hibernate to my SQL database. But for some reason I can't :-/

UPDATE : Hibernate on its own, runs fine. But in conjunction with Spring, these errors occur. (More information in comments).

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
classicjonesynz
  • 4,012
  • 5
  • 38
  • 78
  • Are you sure that hibernate.cfg.xml is located in the classpath? What is the IDE you are using. Why don't you try giving the absolute path to hibernate.cfg.xml in Configuration constructor. – shazin Feb 11 '13 at 05:16
  • 1
    Isn't it possible that your code dies here: `SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();` so it doesn't reach giving session a value? – CsBalazsHungary Feb 11 '13 at 09:56
  • 2
    `Configured SessionFactory: null` is not an error - Hibernate can automatically bind the session factory to JNDI if you specify a `name` attribute to `session-factory` in `hibernate.cfg.xml`. In your case, Hibernate is just logging the session-factory name, which is null. – Hari Feb 11 '13 at 10:57
  • Which line of the `session` method is throwing the NullPointerException? The pastebin log Exception is thrown at FirstExample.java line 40, but it's not clear which line of session() that is. – Hari Feb 11 '13 at 11:01
  • can you share the error log with stack trace – Arun P Johny Feb 11 '13 at 12:14
  • @Hari line 40 is `session.flush();`. – classicjonesynz Feb 11 '13 at 20:34
  • @CsBalazsHungary yeah it could be possible that it is dying there, I don't really know on how I could fix it though. – classicjonesynz Feb 12 '13 at 02:43
  • @shazin I don't really want to give it an absolute path, I prefer relative paths for when it comes to compressing it into a war file. – classicjonesynz Feb 12 '13 at 02:44
  • Added a `tree /f` of the project setup. – classicjonesynz Feb 12 '13 at 02:57
  • Do you already have a value for "13" in the prime table? – hd1 Feb 12 '13 at 02:58
  • @hd1 no the table is completely empty. – classicjonesynz Feb 12 '13 at 03:00
  • I've been reading topics from google `java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.(I)`, could `asm` be causing a conflict?.. because my application is templated from the `New Web Application > Frameworks` (Spring MVC + Hibernate, [jar screendump](http://iforce.co.nz/i/dhly0exp.1p4.png)). – classicjonesynz Feb 13 '13 at 21:34
  • Hibernate on its own, runs fine. But in conjunction with Spring, these errors occur. – classicjonesynz Feb 13 '13 at 22:23

2 Answers2

5

It looks like you're missing a library that Hibernate needs at run time. I saw the same behavior as you with your code (MySQL 5, MySQL JDBC driver, Mac OS) until I changed the line:

catch (Exception e) {
      System.out.println(e.getMessage());
}

To:

catch (Throwable e) {
       e.printStackTrace();
}

I then started seeing a whole set of NoClassDefFoundError and ClassNotFoundError messages about libraries that Hibernate was looking for but were not included in my CLASSPATH. I suspect that you're missing a library that Hibernate needs, and because you're catching Exception and not Throwable - which catches Error - you're not seeing the error message. See:

Why catch Exceptions in Java, when you can catch Throwables?

If you catch the Throwable you'll see fairly quickly what libraries and classes you're missing: my guess would be that you're probably missing EHCache (which Hibernate seems to use as a second-level cache by default), CGLIB/ASM, or the Java Transaction API. If you're missing EHCache and you want hibernate to use its own, in-memory Hashtable cache instead of EHCache, add the line below to hibernate.cfg.xml:

<property name="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>

Update, based on comments to answer:

I don't use NetBeans and so I haven't run into this problem, but it appears fairly widespread. See:

Error : java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V

http://www.hildeberto.com/2008/05/hibernate-and-jersey-conflict-on.html (Reports a similar problem with Hibernate and Jersey in Netbeans)

https://hibernate.onjira.com/browse/HHH-2222 (Hibernate bug report mentioning this problem)

http://netbeans.org/bugzilla/show_bug.cgi?id=145589 (Netbeans bug report for bundled Hibernate using older versions of cglib).

The StackOverflow post linked to above has quite a lot of detail. To summarize:

  • Hibernate 3.2 uses CGLib 2.1.3 for run-time code generation, to improve performance and to generate proxies for one-to-one and one-to-many mappings.

  • CGLib is a higher-level wrapper around ASM, a bytecode manipulation library. CGLib 2.1.3 requires ASM 1.5.3, which is binary incompatible with ASM 2.2. ASM 2.2 in turn is a dependency for Spring versions < 2.5.

  • To resolve these problems between Hibernate and Spring, Spring 2.5 bundles its own version of asm with a spring package name; later versions of Hibernate use CGLIB 2.2, which also bundles its own version of ASM with a custom package name. The most recent versions of Hibernate do away with CGLIB altogether and use Javassist instead, but NetBeans still bundles Hibernate 3.2.5.

You have a few options, then:

  • Update the Hibernate library package in Netbeans with CGLIB 2.2

  • Tell Hibernate to use Javassist for runtime code generation. Add this line to hibernate.properties, or specify it as a system property using -D (you can't specify this property in hibernate.cfg.xml, apparently):

    hibernate.bytecode.provider=javassist

Good luck, this has been rather an interesting question!

Community
  • 1
  • 1
Hari
  • 1,056
  • 1
  • 10
  • 13
  • Thanks ! Hari! :D +1 rep, will mark once I test your solution. Thanks again! :) – classicjonesynz Feb 13 '13 at 03:57
  • Hey Hari, the [Throwable Stacktrace](http://pastebin.com/kd7Ssykr) says something about `java.lang.NoSuchMethodError` with occurrences in packages such as `net.sf.cglib.core` (but all these classes exist in the `lib` folder). – classicjonesynz Feb 13 '13 at 21:17
  • 1
    @Killrawr My guess is that the `java.lang.NoSuchMethodError` is coming from mis-matched versions of JARs on your classpath. Make sure you are using compatible versions of all of your third-party libs! – Jesse Webb Feb 13 '13 at 22:38
  • @JesseWebb Hey the class path for Spring MVC and Hibernate are pre configured from netbeans, `New Project > New Web Application > Frameworks (Select Spring and Hibernate)`, seen [here](http://iforce.co.nz/i/llroxgez.s5s.png). – classicjonesynz Feb 14 '13 at 01:23
  • @Hari hey hari, just trying your solution now. My project doesn't have a `hibernate.properties` ([hibernate properties](http://netbeans.org/kb/docs/web/hibernate-webapp.html)), what should the `.properties` file look like? – classicjonesynz Feb 17 '13 at 21:29
  • The properties file should look like this: `hibernate.bytecode.provider=javassist` – Hari Feb 18 '13 at 11:20
  • Do I need to include it within the class path? – classicjonesynz Feb 18 '13 at 21:42
  • 1
    If you place hibernate.properties in the "" section under "Source Packages" in NetBeans, it will get included automatically. If you didn't create hibernate.properties from within NetBeans, just place hibernate.properties in the classpath root (in a NetBeans Web Application projet, in `build/web/WEB-INF/classes`). In that directory, you should have: `hibernate.cfg.xml hibernate.properties prime.hbm.xml nz/` – Hari Feb 19 '13 at 11:23
  • Thanks Hari! it worked :D, just gave you the bounty on the question :) – classicjonesynz Feb 19 '13 at 20:39
-1

It is dying at session.flush(); because session is null and something in the try-block is throwing an exception, probably a runtimeexception like nullpointer or something. The fact that the session is null will cause another nullptr and it will hide the original one. So I suggest that you make it

if(session!=null)
{
    session.flush();
    session.close();
}

and then run it to see what the actual problem is.

I also suggest that you replace the "System.out.println(e.getMessage());" with atleast e.printStackTrace(); or preferably proper logging.

Markus Mikkolainen
  • 3,397
  • 18
  • 21
  • also the inserts with ? -values are a common syntax for a prepared query with parameters. – Markus Mikkolainen Feb 12 '13 at 07:35
  • I've already tried this before submitting the question, thanks for the proposed solution though. – classicjonesynz Feb 13 '13 at 03:58
  • well if you could ofcourse have then posted the resulting exception, since it is bound to be different from the one you posted. – Markus Mikkolainen Feb 13 '13 at 06:40
  • I don't typically believe your answer, answers the question. Although it may stop the `NullException` from occuring. It does not however address the original problem from which hibernate is attempting to insert data. Regards – classicjonesynz Feb 14 '13 at 01:19