/** * @author Deepak Kumar * * http://www.roseindia.net * Hibernate example to inset data into Contact table */ 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"); File file = new File("D:\\bea\\user_projects\\w4WP_workspaces\\Untitled\\Hyber\\hibernate.cfg.xml"); //yu see I have used full path // This is my first run I will chenge to relative path later System.out.println(file.exists()); SessionFactory sessionFactory = new Configuration().configure(file).buildSessionFactory(); if(sessionFactory == null) { System.out.println("NULL"); //Testing it } else { System.out.println("NOT 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();
}
}
}
Error is
getEventInfo true Exception in thread "Main Thread" java.lang.NullPointerException at roseindia.tutorial.hibernate.FirstExample.main(FirstExample.java:52)
SCJP1.4<br />SCWCD1.5<br />"Nothing is impossible"
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper
Actually also looking at your code I see you have this
If you have your hibernate.cfg.xml in the root of your classpath, then you do not need to create a File object and use that method version to create your SessionFactory.
You can simple do
SessionFactory sessionFactory = new Configuration().configure.buildSessionFactory();
Here is the most common way people do. The make a HibernateUtil class like
I stole that completely from the hibernate.org documentation page.
Mark
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper
I am also having the same problem, null pointer exception. Please help me out. I have hibernate.cfg.xml in /src directory so that its automatically included to build path.
Originally posted by labi laba: I am also having the same problem, null pointer exception. Please help me out. I have hibernate.cfg.xml in /src directory so that its automatically included to build path.
Can you create a new thread for your issue.
Include your pathing, classpath, and your hibernate.cfg.xml and how you package it all up