Solved

Problem in Running Hibernate Sample application

Posted on 2009-05-06
16
1,234 Views
Last Modified: 2013-11-24
HI experts,

              I am trying to run the sample hibernate application from www.roseindia.com, but its giving me a null pointer exception, whenever I am trying to run the below stated code. I have also added the hibernate3.jar and ojdbc14.jar in the class path.

              Please help me out running this small application.
package roseindia.tutorial.hibernate;
 

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;
 
 

public class FirstExample {

	

  public static void main(String[] args) {

    Session session = null;
 

    try{

      
 
 

      SessionFactory sessionFactory = new 
 

Configuration().configure().buildSessionFactory();

       session =sessionFactory.openSession();

        //Create new instance of Contact and set 
 
 

         System.out.println("Inserting Record");

        Contact contact = new Contact();

        contact.setId(3);

        contact.setFirstName("Deepak");

        contact.setLastName("Kumar");

        contact.setEmail("abc@yahoo.com");

        session.save(contact);

        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();
 

      }

    

  }

}

Open in new window

Folder-Structure.PNG
0
Comment
Question by:aman0711
  • 10
  • 5
16 Comments
 
LVL 10

Author Comment

by:aman0711
ID: 24320488
I tried to modify it and now the both the configuration files are in the src folder, I also added few jars.
I have attached the folder snap shot.

Exception in thread "main" java.lang.NullPointerException

	at roseindia.tutorial.hibernate.FirstExample.main(FirstExample.java:36)

Open in new window

Folder-Structure.PNG
0
 
LVL 10

Author Comment

by:aman0711
ID: 24320593
Anyone? Someone? :-)

I tried to put in some print statements to test it in the following code

Its printing the getEvenInfo.... and after this on the console its printing:

May 6, 2009 5:32:36 PM org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: using driver: oracle.jdbc.driver.OracleDriver at URL: jdbc:oracle:thin:@ppld01.abc.xyz.com:1521:opwk007

along with some other details. So that means its reading one of the configuration file.

but after that the execution is never reaching

SessionFactory sessionFactory = new Configuration().configure()
                    .buildSessionFactory();
            if (sessionFactory == null) {
                System.out.println("NULLLLLLLLLLLLLLLLLLLLLLLL"); // Testing it
            } else {
                System.out.println("NOTTTTTTTTTTTTTTTTTTTTTTTTTT NULL");
            }

package roseindia.tutorial.hibernate;
 

import org.hibernate.Hibernate;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;
 

public class FirstExample {

	public static void main(String[] args) {

		Session session = null;
 

		try {

			// This step will read hibernate.cfg.xml and prepare hibernate for

			// use

			System.out.println("getEventInfo");

			

		
 

			SessionFactory sessionFactory = new Configuration().configure()

					.buildSessionFactory();

			if (sessionFactory == null) {

				System.out.println("NULLLLLLLLLLLLLLLLLLLLLLLL"); // Testing it

			} else {

				System.out.println("NOTTTTTTTTTTTTTTTTTTTTTTTTTT NULL");

			}
 

			// SessionFactory sessionFactory = new

			// Configuration().configure().buildSessionFactory();

			System.out.println("Sessiong Factory After");

			session = sessionFactory.openSession();

			// Create new instance of Contact and set values in it by reading

			// them from form object

			System.out.println("Inserting Record");

			Contact contact = new Contact();

			contact.setId(3);

			contact.setFirstName("Deepak");

			contact.setLastName("Kumar");

			contact.setEmail("deepak_38@yahoo.com");

			session.save(contact);

			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();
 

		}
 

	}
 

}

Open in new window

0
 
LVL 92

Assisted Solution

by:objects
objects earned 150 total points
ID: 24320706
sounds like its not finding your hib configuration
try moving the xml into the src directory (one level up)

and increase the logging so you can see whats going on

0
 
LVL 10

Author Comment

by:aman0711
ID: 24321617
I did that as well Mick.. still didnt work.

Actually, this is the only example of hibernate available for beginners when you google for it.
Tons of people have complained about this example, but no one ever put up the solution.

Can you please give us a solution for this simple example Mick :-) Pleaseeeeeeeeee :)

its a roseindia.com sample application
0
 
LVL 10

Assisted Solution

by:mahome
mahome earned 350 total points
ID: 24323157
I just tried the example and all worked well.

But there are errors in description. Do the following steps after creating eclipse project:
  • Use the root-Folder as source folder for your build path
  • Create your database hibernatetutorial
0
 
LVL 10

Expert Comment

by:mahome
ID: 24323171
For finding the error above change line 42:

and post this stacktrace. Because you error only tells, that session is null due to an unknown error in try block.

System.out.println(e.getMessage());
 

better
 

e.printStackTrace();

Open in new window

0
 
LVL 10

Author Comment

by:aman0711
ID: 24324347
Thanks mahome, give me sometime, I will try this :)
0
 
LVL 10

Author Comment

by:aman0711
ID: 24325592
Hi Mahome,
                        After changing the line 42. This is what i got in the console.

                        Few questions:

                       - How doI use root folder as source folder in Eclipse? (dont use a package? instead move all the java code in the src folder itself?)

 
                       - Create database as hibernatetutorial?

getEventInfo

May 7, 2009 8:37:47 AM org.hibernate.cfg.Environment <clinit>

INFO: Hibernate 3.0rc1

May 7, 2009 8:37:47 AM org.hibernate.cfg.Environment <clinit>

INFO: hibernate.properties not found

May 7, 2009 8:37:47 AM org.hibernate.cfg.Environment <clinit>

INFO: using CGLIB reflection optimizer

May 7, 2009 8:37:47 AM org.hibernate.cfg.Environment <clinit>

INFO: using JDK 1.4 java.sql.Timestamp handling

May 7, 2009 8:37:47 AM org.hibernate.cfg.Configuration configure

INFO: configuring from resource: /hibernate.cfg.xml

May 7, 2009 8:37:47 AM org.hibernate.cfg.Configuration getConfigurationInputStream

INFO: Configuration resource: /hibernate.cfg.xml

May 7, 2009 8:37:47 AM org.hibernate.cfg.Configuration addResource

INFO: Mapping resource: contact.hbm.xml

May 7, 2009 8:37:47 AM org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues

INFO: Mapping class: roseindia.tutorial.hibernate.Contact -> CONTACT

May 7, 2009 8:37:47 AM org.hibernate.cfg.Configuration doConfigure

INFO: Configured SessionFactory: null

May 7, 2009 8:37:47 AM org.hibernate.cfg.Configuration secondPassCompile

INFO: processing extends queue

May 7, 2009 8:37:47 AM org.hibernate.cfg.Configuration secondPassCompile

INFO: processing collection mappings

May 7, 2009 8:37:47 AM org.hibernate.cfg.Configuration secondPassCompile

INFO: processing association property references

May 7, 2009 8:37:47 AM org.hibernate.cfg.Configuration secondPassCompile

INFO: processing foreign key constraints

May 7, 2009 8:37:47 AM org.hibernate.dialect.Dialect <init>

INFO: Using dialect: org.hibernate.dialect.OracleDialect

May 7, 2009 8:37:47 AM org.hibernate.cfg.SettingsFactory buildSettings

INFO: Default batch fetch size: 1

May 7, 2009 8:37:47 AM org.hibernate.cfg.SettingsFactory buildSettings

INFO: Generate SQL with comments: disabled

May 7, 2009 8:37:47 AM org.hibernate.cfg.SettingsFactory buildSettings

INFO: Order SQL updates by primary key: disabled

May 7, 2009 8:37:47 AM org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory

INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory

May 7, 2009 8:37:47 AM org.hibernate.hql.ast.ASTQueryTranslatorFactory <init>

INFO: Using ASTQueryTranslatorFactory

May 7, 2009 8:37:47 AM org.hibernate.cfg.SettingsFactory buildSettings

INFO: Query language substitutions: {}

May 7, 2009 8:37:47 AM org.hibernate.connection.DriverManagerConnectionProvider configure

INFO: Using Hibernate built-in connection pool (not for production use!)

May 7, 2009 8:37:47 AM org.hibernate.connection.DriverManagerConnectionProvider configure

INFO: Hibernate connection pool size: 10

May 7, 2009 8:37:47 AM org.hibernate.connection.DriverManagerConnectionProvider configure

INFO: autocommit mode: false

May 7, 2009 8:37:47 AM org.hibernate.connection.DriverManagerConnectionProvider configure

INFO: using driver: oracle.jdbc.driver.OracleDriver at URL: jdbc:oracle:thin:@plti100.pedc.sbc.com:1521:opwk007

May 7, 2009 8:37:47 AM org.hibernate.connection.DriverManagerConnectionProvider configure

INFO: connection properties: {user=apm, password=****}

May 7, 2009 8:37:47 AM org.hibernate.cfg.SettingsFactory buildSettings

INFO: JDBC batch size: 15

May 7, 2009 8:37:47 AM org.hibernate.cfg.SettingsFactory buildSettings

INFO: JDBC batch updates for versioned data: disabled

May 7, 2009 8:37:47 AM org.hibernate.cfg.SettingsFactory buildSettings

INFO: Scrollable result sets: enabled

May 7, 2009 8:37:47 AM org.hibernate.cfg.SettingsFactory buildSettings

INFO: JDBC3 getGeneratedKeys(): disabled

May 7, 2009 8:37:47 AM org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory

INFO: Using default transaction strategy (direct JDBC transactions)

May 7, 2009 8:37:47 AM org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup

INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)

May 7, 2009 8:37:47 AM org.hibernate.cfg.SettingsFactory buildSettings

INFO: Automatic flush during beforeCompletion(): disabled

May 7, 2009 8:37:47 AM org.hibernate.cfg.SettingsFactory buildSettings

INFO: Automatic session close at end of transaction: disabled

May 7, 2009 8:37:47 AM org.hibernate.cfg.SettingsFactory createCacheProvider

INFO: Cache provider: org.hibernate.cache.EhCacheProvider

Exception in thread "main" java.lang.NullPointerException

	at roseindia.tutorial.hibernate.FirstExample.main(FirstExample.java:46)

Open in new window

0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 10

Assisted Solution

by:mahome
mahome earned 350 total points
ID: 24326040
I'm not sure if we have the same code basis: I downloaded: http://www.roseindia.net/hibernate/hibernate.zip
and then tried to follow http://www.roseindia.net/hibernate/runninge-xample.shtml, but there are errors as mentioned above.

>>How doI use root folder as source folder in Eclipse? (dont use a package? instead move all the java code in the src folder itself?)
No that's not what I ment. In my download the folder structure is as follows.
hibernateexample/roseindia/tutorial/hibernate/FirstExample.java
and the the tutorial says that you should put the net folder into path, but all the example are located under the folder roseindia. Therefore the parentfolder hast to be in the classpath and that is for me the root-folder (hibernateexample) of the application. Looking at your screen shot you did it right, but have another code basis.

>>Create database as hibernatetutorial?
The tutorial didn't mention that you need to create the database. But you need to, otherwise the code doesn't work.

I can't figure out what goes wrong in your app. If the session would be null, the error would be in line 39.
0
 
LVL 10

Author Comment

by:aman0711
ID: 24326093
Hmm, The one I am running is the very basic tutorial of rose india, where you do not need to download any project file.

               but let me try the one you tried, real quick and get back to you :)
0
 
LVL 10

Author Comment

by:aman0711
ID: 24326294
Hi Mahome,
                         Can we start fixing it now. Now I have the same code that you ran. attached it the folder structure, I tried to run it but again a null pointer

new-projct-folder.PNG
0
 
LVL 10

Accepted Solution

by:
mahome earned 350 total points
ID: 24326527
hmm folder structure is correct. Code basis is also the same. Really difficult. We can try finding out with prints: I added some prints as in code snippets:

try{

			// This step will read hibernate.cfg.xml and prepare hibernate for use

			SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

			System.out.println(sessionFactory.getAllClassMetadata());

			 session =sessionFactory.openSession();

			 System.out.println(session);

				//Create new instance of Contact and set values in it by reading them from form object

			 	System.out.println("Inserting Record");

				Contact contact = new Contact();

				contact.setId(6);

				contact.setFirstName("Deepak");

				contact.setLastName("Kumar");

				contact.setEmail("deepak_38@yahoo.com");

				session.save(contact);

				System.out.println(session);

				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();
 

			}
 

---------------------------------

Here is my output:

{roseindia.tutorial.hibernate.Insurance=SingleTableEntityPersister(roseindia.tutorial.hibernate.Insurance), roseindia.tutorial.hibernate.Book=SingleTableEntityPersister(roseindia.tutorial.hibernate.Book), roseindia.tutorial.hibernate.Contact=SingleTableEntityPersister(roseindia.tutorial.hibernate.Contact)}

org.hibernate.impl.SessionImpl(PersistentContext[entitiesByKey={}] ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])

Inserting Record

org.hibernate.impl.SessionImpl(PersistentContext[entitiesByKey={EntityKey[roseindia.tutorial.hibernate.Contact#6]=roseindia.tutorial.hibernate.Contact@4bd53f5b}] ActionQueue[insertions=[EntityInsertAction[roseindia.tutorial.hibernate.Contact#6]] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])

Done

Hibernate: insert into CONTACT (FIRSTNAME, LASTNAME, EMAIL, ID) values (?, ?, ?, ?)

Open in new window

0
 
LVL 10

Author Comment

by:aman0711
ID: 24326576
wow, I am going insane :(

        Tried the exact code as yours. Still no. Though my database name is not hibernateexample, but I guess that shouldnt matter right?

Exception in thread "main" java.lang.NullPointerException

	at roseindia.tutorial.hibernate.FirstExample.main(FirstExample.java:34)

Open in new window

0
 
LVL 10

Author Comment

by:aman0711
ID: 24336804
hey Mahome, at last it worked :)

but i didnt see any data in my table :(
0
 
LVL 10

Expert Comment

by:mahome
ID: 24352608
What did you change to make it work?

I had data in my table.
0
 
LVL 10

Author Comment

by:aman0711
ID: 24354709
Actually nothing. Deleted the complete project from workspace, re-imported again. and worked this time.


0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
The viewer will learn how to implement Singleton Design Pattern in Java.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now