Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Spring Framework | Web Services | BioInformatics | Java Server Faces | Jboss 3.0 tutorial | Hibernate 3.0 | XML

Tutorial Categories: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML


 

Java Tutorials


 

 

Struts Tutorials

Struts Resources

Visit Forum! Post Questions!
Jobs At RoseIndia.net!

Hibernate Firstexample

User Comments
Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl
  Blink   Furl   Simpy   Y! MyWeb 

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

236 comments so far (post your own) View All Comments Latest 10 Comments:

The tutorial you provided is excellent but if you provide the space that where to put hibernate.cfg.xml & contact.hbm.xml then it will be more useful for us

thank you

Posted by Isaq Zarekari on Thursday, 10.14.10 @ 17:22pm | #100285

hai this is my comment







Posted by Anand on Thursday, 10.7.10 @ 15:55pm | #100104

roseindia/tutorial/hibernate/FirstExample do u have ur java class in this path? if not create it or else change the path according to your java class file path

Posted by Jagan on Friday, 09.3.10 @ 15:29pm | #99342

The FirstExample is not working when u use oracle database.so u need to add those two more lines in the program i.e. tx = session.beginTransaction(); before Contact contact = new Contact(); and tx.commit(); after session.save(contact);

Posted by Dillip on Tuesday, 08.24.10 @ 14:42pm | #99121

I Try to write this tutorial and
in my eclipse console white this:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" java.lang.NullPointerException
at roseindia.tutorial.hibernate.FirstExample.main(FirstExample.java:35)
/hibernate.cfg.xml not found



please help :):)

Posted by igor on Monday, 08.16.10 @ 18:03pm | #98962

Could not get the result when executing hibernate first example:
pls help me

Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Cannot open connection
at org.hibernate.exception.ErrorCodeConverter.convert(ErrorCodeConverter.java:67)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
at org.hibernate.jdbc.AbstractBatcher.openConnection(AbstractBatcher.java:384)
at org.hibernate.jdbc.JDBCContext.connect(JDBCContext.java:141)
at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:88)
at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:73)
at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:66)
at org.hibernate.jdbc.AbstractBatcher.prepareBatchStatement(AbstractBatcher.java:130)
at org.hibernate.persister.entity.BasicEntityPersister.insert(BasicEntityPersister.java:1809)
at org.hibernate.persister.entity.BasicEntityPersister.insert(BasicEntityPersister.java:2171)
at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:46)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:239)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:223)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:136)

Posted by Karthi on Friday, 08.13.10 @ 07:57am | #98885

SessionFactory sessionFactory = new

Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
// The below transaction element is not initialized and commited
Transaction trans = session.beginTransaction();
//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);
trans.commit();
System.out.println("Done");

Posted by Mahesh on Thursday, 08.12.10 @ 14:24pm | #98865

please add the two line in hibernate first exemple ok

Transaction tx=session.beginTransaction();


tx.commit();

Posted by Shiva Nooka on Wednesday, 08.4.10 @ 22:39pm | #98696

Very very thanks for providing such a useful coding . b'cause of you only we can understand the new technology throughly. plz try to give step 1 step2 ..like so very novice programmer also can understand about configuration

Posted by rahul on Tuesday, 07.27.10 @ 20:08pm | #98476

how i can learn this topic

Posted by sunil on Sunday, 07.25.10 @ 13:03pm | #98422

this site gives very good information....

Posted by swathi on Tuesday, 07.20.10 @ 23:30pm | #98320

After adding the Tranasaction part, the code works perfectly fine by adding the records into the database.
Thanks for a very good tutorial for the beginners.

Posted by Savitha on Sunday, 07.18.10 @ 22:40pm | #98270

here is the code that works!

public static void main(String[] args) {
// TODO code application logic here

Session session = null;

try{
// This step will read hibernate.cfg.xml

System.out.println("creating session factory");

SessionFactory sessionFactory = new Configuration().
configure(new File("D:\\NetBeansProjects\\Hibernate\\src\\hibernate\\hibernate.cfg.xml"))
.buildSessionFactory();
session =sessionFactory.openSession();
//Create new instance of Contact and set


System.out.println("Inserting Record");
User contact = new User();

contact.setEmailAddress("vic@vic.com");
contact.setLastLogon(new Date());
contact.setPassword("pass");
contact.setUserID("n2342");
contact.setUserName("Victor");

Transaction tx=session.beginTransaction();

session.save(contact);
tx.commit();

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

}


}

Posted by Victor Aguilera on Monday, 06.14.10 @ 23:04pm | #97579

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


to

session =sessionFactory.openSession();
Trnsaction tx=session.beginTransaction();
//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);
tx.commit();

Posted by Nandha on Thursday, 06.10.10 @ 15:43pm | #97499

This tutorial is very much useful for any beginner who wants to excel conceptuaaly and practically in hibernate .It covers every thing to learn and understand hibernate.

Posted by balaswamy vaddeman on Friday, 04.16.10 @ 15:18pm | #96427

every thing is very basic and easily understable. but dint mention how and where to create new .hbm.xml ?

Posted by mrinal on Wednesday, 04.14.10 @ 12:27pm | #96360

This examples and explanation is very good .

Posted by sree on Wednesday, 03.17.10 @ 19:22pm | #95643

how to solve the error reading resource in insurance .hbm.xml files in association and join example.

please reply me it is very urgent. no one has posted the proper answer .

your tutorial is really good i am new to hibernate but now i am able to create simple application.




Posted by swetha on Tuesday, 02.23.10 @ 12:10pm | #95061

Please add the below lines.
Transaction tx=session.beginTransaction()
tx.begin();

Before session.save()

and
tx.commit(); after it.

This should work :)

Posted by Shreenivasan Bhardwaj on Friday, 02.19.10 @ 10:48am | #94945

In this page we can't run this first Hibenate code example.Because of FirstExample.java class must have following two statements in the main method.


org.hibernate.Transaction tx = session.beginTransaction();

tx.commit();


please correct them. thanks.

Posted by Charitha on Thursday, 02.18.10 @ 17:04pm | #94937

i see nullpointer exception at session

Posted by bayarja on Thursday, 02.18.10 @ 09:35am | #94920

I am getting the following error, when i try to run a sample application, could you please let me know, what should have happened wrong....?

Initial SessionFactory creation failed.org.hibernate.InvalidMappingException: Could not parse mapping document from resource org/hibernate/tutorial/domain/Event.hbm.xml
Exception in thread "main" java.lang.NullPointerException
at org.hibernate.tutorial.EventManager.createAndStoreEvent(EventManager.java:24)
at org.hibernate.tutorial.EventManager.main(EventManager.java:13)

Posted by Kiran on Tuesday, 02.16.10 @ 03:20am | #94868

After building nad running I get the following error
Exception in thread "main" java.lang.NoClassDefFoundError: roseindia/tutorial/hibernate/FirstExample
Caused by: java.lang.ClassNotFoundException: roseindia.tutorial.hibernate.FirstExample
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:315)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:330)
at java.lang.ClassLoader.loadClass(ClassLoader.java:250)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:398)
I hvae used first example code.

Posted by Nikhil Dhavale on Tuesday, 02.9.10 @ 03:00am | #94670

After using Transaction tx=session.beginTransaction();
tx.commit();
Still the same prob exists. plz tel a solution

Exception in thread "main" java.lang.NoClassDefFoundError: FirstExample (wrong n
ame: roseindia/tutorial/hibernate/FirstExample)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:12
4)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
at java.net.URLClassLoader.access$000(URLClassLoader.java:56)
at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)

Thanks in advance
vaidya

Posted by vaidyanathan on Thursday, 01.21.10 @ 15:27pm | #94205

This site contians lot of programming stuff that helps developers and students.

Posted by utpal on Wednesday, 01.20.10 @ 13:56pm | #94173

Exception in thread "main" org.hibernate.HibernateException: Hibernate Dialect must be explicitly set

No one had given proper answer to resolve this error

Posted by Bala on Tuesday, 01.19.10 @ 11:05am | #94131

when i execute the program i am getting null pointer exception.i didn't create any database...can u pls help me..i am new in hiberate..please

Posted by greeshma on Friday, 01.15.10 @ 01:03am | #94043


package roseindia.tutorial.hibernate;

import java.io.Serializable;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;


/**
* @author Gunjan 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
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();


Transaction tx = session.beginTransaction();
//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(11);
contact.setFirstName("Gunjan");
contact.setLastName("Kumar");
contact.setEmail("gunjan0326@gmail.com");
System.out.println("contact----------->" + contact);
Serializable p = session.save(contact);
tx.commit();



System.out.println("Serializable------->" + p);
System.out.println("Done");
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
// Actual contact insertion will happen at this step


session.flush();

System.out.println("Done1");
session.close();
System.out.println("Done2");

}

}
}

Posted by gunjan on Thursday, 01.14.10 @ 17:03pm | #94036

may be this enty helps
<property name="connection.autocommit">true</property>

Posted by Welchlin on Wednesday, 01.13.10 @ 21:59pm | #94021

session.beginTransaction().commit();

Add this after session.save(contact);

it will work

Posted by parth on Friday, 12.11.09 @ 11:20am | #93284

Im new to this hibernate.

When i try to run the FirstExample.java class im getting the followning error ::: Cannot open connection



I have change my hibernate.cfg.xml file as like this ::


<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@10.90.1.7:1521:DEVEL</property>
<property name="hibernate.connection.username">scott</property>
<property name="hibernate.connection.password">lion</property>
<property name="hibernate.connection.pool_size">5</property>
<property name="show_sql">true</property>
<property name="dialect"> org.hibernate.dialect.Oracle9Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="roseindia.contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>


and i have the FirestExample.java code is:

Session session = null;
//Transaction trans =null;
try{
/** This step will read hibernate.cfg.xml and prepare hibernate for use**/

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session=sessionFactory.openSession();
Transaction tx=session.beginTransaction();

System.out.println("Inserting Record");
Contact contact=new Contact();

contact.setFirstName("Deepak");
contact.setLastName("kumar");
contact.setEmail("pra@yahoo.com");
contact.setId(3);
session.save(contact);
System.out.println("Done");
tx.commit();
}catch(Exception e){
System.out.println("Exception Occured::: " +e.getMessage());
//trans.rollback();
}finally{
/**Actual contact insertion will happen at this step**/

session.close();


}





plz suggest me how to run thhe hibernate code.

Posted by Sam on Friday, 11.27.09 @ 15:15pm | #92892

add these:-
import org.hibernate.Transaction;

then before S.o.p("Inserting records") add the below:-
Transaction tx = session.beginTransaction();
then after S.o.p("Done"); add:-
tx.commit();

when ever u insert anything to DB
u must commit or else it will show inserted result in eclipse but when u check it woudnt hve been....

Posted by susheel on Tuesday, 11.17.09 @ 15:40pm | #92641

add these:-
import org.hibernate.Transaction;

then before S.o.p("Inserting records") add the below:-
Transaction tx = session.beginTransaction();
then after S.o.p("Done"); add:-
tx.commit();

when ever u insert anything to DB
u must commit or else it will show inserted result in eclipse but when u check it woudnt hve been....

Posted by susheel on Tuesday, 11.17.09 @ 15:36pm | #92640

check your finally clause if there is no session yet you
can't flush() nor close() it. Make that finally clause:
if (session != null) {
session.flush();
session.close();
}
if you write directly finally clause like
finally{
session.flush();
session.close();
}
it will give Nullpointer exception.

Posted by sachin on Monday, 11.9.09 @ 12:00pm | #92435

Add the following line
session.beginTransaction().commit();
after session.save(contact);

Posted by saradhij2ee on Sunday, 10.25.09 @ 18:35pm | #92111

do you have hibernate.cfg.xml
in the classpath.

Posted by praful on Tuesday, 10.6.09 @ 10:03am | #91459

Upon running the code in the First example. I keep getting the session object as null.

How to overcome this?

Posted by Priety on Saturday, 09.26.09 @ 17:50pm | #91218

i m getting NULL POINTER EXCEPTION when a empty string is passed to a method.i m using NETBEANS IDE6.5.
can anyone help me?

Posted by Balaji on Saturday, 09.19.09 @ 21:30pm | #91057

nullpointerexception

Posted by preethi on Friday, 09.18.09 @ 11:57am | #91017

i am new to hibernate. when i used to execute this program it shows inserting record and cannot open connection and shows (Exception in thread "main" org.hibernate.exception.GenericJDBCException: Cannot open connection)

Posted by balamurugan on Saturday, 09.12.09 @ 16:21pm | #90856

Hi ,
In the class FirstExample ,I dont see that we are passing any reference of hibernate.cfg.xml then how will the code knows what file to load and where to find it .

I am new to hibernate and I have never seen any code in java where we dont pass the reference of a file and even then the code loads it.Please provide your comments

Thanks,
Harman

Posted by Harman on Friday, 09.4.09 @ 14:30pm | #90581

Here in the above example you did not use Transaction. But i could not insert data without using Transaction interface. I used directly session.save() without using Transaction, but i could not insert the record.

Posted by Anand on Tuesday, 09.1.09 @ 12:02pm | #90478

u have to enable transactions for non select opreations like update delete,insert operations see the code below

System.out.println("Inserting Record");
Transaction tx=session.openTransaction()
Contact contact = new Contact();
contact.setId(6);
contact.setFirstName("Deepak");
contact.setLastName("Kumar");
contact.setEmail("deepak");
session.save(contact);
tx.commit
System.out.println("Done");
}catch(Exception e){
System.out.println("in Exception");
System.out.println(e.getMessage());
}finally{
// Actual contact insertion will happen at this step
System.out.println("the finally block");
session.flush();
session.close();
System.out.println("out of finally");
}

System.out.println("Inserting Record");
Contact contact = new Contact();
contact.setId(6);
contact.setFirstName("Deepak");
contact.setLastName("Kumar");
contact.setEmail("deepak");
session.save(contact);
System.out.println("Done");
}catch(Exception e){
System.out.println("in Exception");
System.out.println(e.getMessage());
}finally{
// Actual contact insertion will happen at this step
System.out.println("the finally block");
session.flush();
session.close();
System.out.println("out of finally");
}

Posted by sandeep on Thursday, 08.27.09 @ 21:32pm | #90367

Session ses=new Configuration().configure("/hibernate cfg file").buildSessionfactory().openSession


this code will slove your problem

Posted by sandeep on Thursday, 08.27.09 @ 21:25pm | #90366

I am getting null pointer exception at SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

Can anyone help me?

Posted by Ranjith on Thursday, 08.27.09 @ 16:00pm | #90356

Can I do multiple inserts within same session / transaction?
But it was failed for me.
See the example below :

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
org.hibernate.Transaction tx = session.beginTransaction();
Contact contact = new Contact();
contact.setId(1);
contact.setFirstName("Deepak");
contact.setLastName("kumar");
contact.setEmail("deepak_kumar@yahoo.com");
session.save(contact);
Contact contact = new Contact();
contact.setId(2);
contact.setFirstName("Ramesh");
contact.setLastName("Aravind");
contact.setEmail("Ramesh_Aravind@yahoo.com");
session.save(contact);
tx.commit();

Posted by Viswanathan Saravanan on Wednesday, 08.19.09 @ 11:38am | #90133

Looks Great! and simple to understand the concept

Posted by Srinivas on Wednesday, 08.12.09 @ 07:32am | #89958

I alredy tried with window.open..

Using stryts class how to disable the refresh button

Also how to hide the url in address bar in struts platform

Posted by Arafat on Saturday, 08.8.09 @ 22:38pm | #89878

Please correct the above example/ This wont work as its not bound to a Hibernate transaction.

I copy pasted the code and evrything worked fine till I queried the DB there are no inserts happening if you runit.

I found that code is missing sesion.beginTransaction() and session.getTransaction().commit()
blocks.

Hope this helps

Ciao

Posted by Rohit on Wednesday, 07.8.09 @ 08:36am | #89134

hi, when I implement an example like the this one(FirstExample.java), it does not insert anything, also does not give any error or warning. Does anybody have an idea where I am doing wrong ??

Posted by halo on Tuesday, 06.30.09 @ 19:37pm | #88929

it is very helpful.nice example.

Posted by dibya on Tuesday, 05.19.09 @ 12:18pm | #87815

Thanks Mahesh..!!

Posted by Rahul on Tuesday, 04.21.09 @ 15:33pm | #87001

Set property name="dialect" org.hibernate.dialect.OracleDialect. After that ur code will work.

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@10.113.48.126:1521:SpringDB</property>
<property name="hibernate.connection.username">springuser</property>
<property name="hibernate.connection.password">Hello123</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>

Posted by Amit Kumar Gupta on Monday, 04.20.09 @ 14:11pm | #86947

good example to start the hibernate learning

Posted by praveen kumar on Sunday, 04.19.09 @ 03:18am | #86924

I too get the same exception. could any1 please explain on this

Thanks

Posted by Sharadha on Thursday, 04.9.09 @ 17:28pm | #86688

Thanks for such nice tutorial..

It is really a good example to start with Hibernate. but unfortunately this code contains one bug.

I had tried to run this demo, but it won't work due to one missing sentence.

To insert data in database you have to commit your transaction.

try this "session.connection().commit();"

this will commit the transactions you have performed. until you commit transactions, your changes won't be reflected in database.

Posted by Dipesh Bhavsar on Tuesday, 03.31.09 @ 12:04pm | #86359

It is very easy to learn the hibernate with ina less span of time and very helpful for understanding the concept clearly.

Thanks for roseindia.net

Posted by Gopinadh on Tuesday, 03.31.09 @ 11:21am | #86358

It is very easy to learn the hibernate with ina less span of time and very helpful for understanding the concept clearly.

Thanks for roseindia.net

Posted by Gopinadh on Tuesday, 03.31.09 @ 11:20am | #86357

I like the example and followed the entire thread. I am able to run my first hibernate application.

Kudos !!

Posted by sourabh jain on Monday, 03.9.09 @ 08:03am | #85649

I would like to tell the webmaster "thank you!" because every time I'm trying using a framework for the first time and need an example the better and clearer explanation I always find here (among all examples I found in the Internet the only one's working is this site's... THANX!!! =)

Posted by Federica on Friday, 03.6.09 @ 05:29am | #85558

Hi,

Core interface Transaction stuff has been missed out in FirstExample.java program.

After Session object initialization, org.hibernate.Transaction tx = null;

After opening the session
tx = session.beginTransaction();

Before fulshing the session
tx.commit();

Correct me if i am wrong.

Regards
Naren

Posted by KK on Tuesday, 03.3.09 @ 06:33am | #85429

Which jar files are required to run the above code?

Posted by prasad on Monday, 03.2.09 @ 04:43am | #85384

Which jars are required for hibernate?

Posted by Prasad Joshi on Monday, 03.2.09 @ 03:02am | #85373

hi,
when compile FirstExample.java class i am getting the following error
Exception in thread "main" java.lang.NullPointerException
at FirstExample.main(FirstExample.java:30)

Posted by raju on Tuesday, 02.24.09 @ 01:26am | #85153

HI,

After compiling this i am getting in the fallowing way "Hibernate Dialect must be explicitly set"

looking for comment

Posted by vijay on Thursday, 02.12.09 @ 05:25am | #84753

Change the FisrtExample.java file as
import org.hibernate.Transaction;//added
Contact contact = new Contact();
Transaction tx = session.beginTransaction();//added

contact.setId(3);
contact.setFirstName("Deepak");
System.out.println("alksdjfl");
contact.setLastName("Kumar");
contact.setEmail("deepak_38@yahoo.com");
session.saveOrUpdate(contact);

tx.commit();//added

Posted by Shailja on Thursday, 02.5.09 @ 04:44am | #84520

It is really helpful. I would like to know how to use oracle10g insted of MYSQL

Posted by Benny on Sunday, 02.1.09 @ 23:55pm | #84385

I need to have the lesson about hibernate in a french version.

Posted by DIALLO on Tuesday, 12.30.08 @ 09:02am | #83316

This is definitely beneficial, it provides clear sample codes of how Java could be used to build applications

Posted by Venkatesa Balasubramanian on Monday, 12.29.08 @ 02:22am | #83248

First Example

Posted by Sridhar on Friday, 12.26.08 @ 05:50am | #83186

[org.hibernate.cfg.Configuration] : Preparing to build session factory with filters : {}
[org.hibernate.cfg.Configuration] : processing extends queue
[org.hibernate.cfg.Configuration] : processing collection mappings
[org.hibernate.cfg.Configuration] : processing native query and ResultSetMapping mappings
[org.hibernate.cfg.Configuration] : processing association property references
[org.hibernate.cfg.Configuration] : processing foreign key constraints
Exception in thread "main" java.lang.AbstractMethodError: org.ops4j.pax.logging.slf4j.Slf4jLogger.isTraceEnabled()Z
at org.hibernate.type.NullableType.<clinit>(NullableType.java:59)
at org.hibernate.Hibernate.<clinit>(Hibernate.java:103)
at org.hibernate.type.TypeFactory.<clinit>(TypeFactory.java:69)
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:283)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:276)
at org.hibernate.mapping.Property.isValid(Property.java:207)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:458)
at org.hibernate.mapping.RootClass.validate(RootClass.java:215)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1135)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1320)
at util.HibernateUtil.initSessionFactory(HibernateUtil.java:68)
at util.HibernateUtil.getInstance(HibernateUtil.java:30)
at data.EventManager.creatAndStoreEvent(EventManager.java:32)
at data.EventManager.main(EventManager.java:26)

Posted by Rajnikanth on Tuesday, 12.23.08 @ 09:20am | #83099

There is a problem. In this "FirstExample" class
session =sessionFactory.openSession();
//Create new instance of Contact and set

//Here transaction should begin.

Transaction trx = session.beginTransaction();


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

// Transaction should be commited here

trx.commit();

System.out.println("Done");



If we dont mention the transaction the database will not update.

In this "FirstExample" class Transaction commit is missing.
Please update the class. It is very helpful for the beginners.

Posted by K.Senthuran on Thursday, 12.18.08 @ 06:40am | #82921

this is excelent

thanks for this

Posted by raghava on Tuesday, 12.16.08 @ 12:13pm | #82837


After
session.save(contact);
add
session.beginTransaction().commit();
or
session.connection().commit();

I think it will solve ur problem

Posted by mahesh on Wednesday, 12.3.08 @ 22:21pm | #82347

what to do if problem is in session.i need to add any jar files to the classpath

Posted by sujatha on Thursday, 11.20.08 @ 15:15pm | #81868

Thanks for the example given on hibernate but when i was executing the code iam geting following Exception in thread "main" java.lang.NullPointerException
at Hibernate.FirstExample.main(FirstExample.java:34)

Posted by kanak vasudeva on Wednesday, 11.12.08 @ 22:37pm | #81622

THANKS GUYS .... KEEP POSTING :)

Posted by Prashanth on Wednesday, 11.12.08 @ 13:24pm | #81619

Hi,

Inspite of having all the below jars in the classpath,

antlr-2.7.6.jar,
commons-collections-3.1.jar,
commons-logging-1.0.jar,
dom4j-1.6.1.jar,
javassist-3.4.GA.jar,
jta-1.1.jar,
slf4j-api-1.5.3.jar,
slf4j-jcl-1.5.3.jar

I am still getting the nullpointerexception.

Exception in thread "main" java.lang.NullPointerException
at roseindia.tutorial.hibernate.FirstExample.main(FirstExample.java:37)

Can any one please help me on how to go on this?

Thanks & Regards,
HariKrishna.P

Posted by Harikrishna on Tuesday, 11.11.08 @ 11:22am | #81591

Exception in thread "main" java.lang.NullPointerException
at pack.FirstExample.main(FirstExample.java:41)

Posted by amit on Tuesday, 11.4.08 @ 19:16pm | #81518

when i was executing the code FirstExample.java

i am getting NULL POINTER EXCEPTION at the line

session.flush().

can anybody helps me in solving this problem.....

Posted by Raju Bejjanki on Wednesday, 10.29.08 @ 00:58am | #81376

hi ,

can anyone help me out , when i run the FirstExample.java file then i am getting an error as " Exception in thread main , java.lang.NullPointerException".

Posted by lakshmikanth on Monday, 10.27.08 @ 16:46pm | #81352

hi when i am running this example then i am getting nullpointer exception like "Exception in thread "main" java.lang.NullPointerException" ..please anyone help me

Posted by suresh on Sunday, 10.26.08 @ 12:15pm | #81330

I also finds the same problem...
Exception in thread "main" java.lang.NullPointerException

Posted by anakTani on Saturday, 10.25.08 @ 10:15am | #81313

I too faced this problem and solved it like this
u need to add the following lines
session = sessionFactory.openSession();
--------------------------------------------
Transaction txn = session.beginTransaction();
---------------------------------------------
and after
session.save() add
-------------
txn.commit()
-------------
this problem i faced with oracle which does not insert data without commit

Posted by gururaj on Friday, 10.24.08 @ 17:55pm | #81303

hi,
I study your web, in that ejb,Hibernate it gives very detail with sutable example, architecture and brief description so it is very easy to understand..........

Thanks.....
Dnyaneshwar S. Panchal

Posted by dnyaneshwar on Wednesday, 10.22.08 @ 22:04pm | #81252

to the dudes having NPE - additional libraries are required:
antlr-2.7.6.jar,commons-collections-3.1.jar,commons-logging.jar,dom4j-1.6.1.jar,javassist-3.4.GA.jar,jta-1.1.jar,slf4j-api-1.5.3.jar,slf4j-jcl-1.5.3.jar

see hibernate distribution

Posted by Tom on Monday, 10.6.08 @ 16:30pm | #80927

I have same problem.

Posted by paul on Thursday, 10.2.08 @ 04:02am | #80831

i'm using netbean 6.1 but when it run it have error
com.mysql.jdbc.Driver not found.I see com.mysql.jdbc.Driver is installed width hibernate.
Why i have this problem?

Posted by hoa phạm on Wednesday, 10.1.08 @ 19:42pm | #80826

NO INSERTION HAPPENS!!

System.out.println("Inserting Record");
Contact contact = new Contact();
contact.setId(6);
contact.setFirstName("Deepak");
contact.setLastName("Kumar");
contact.setEmail("deepak");
session.save(contact);
System.out.println("Done");
}catch(Exception e){
System.out.println("in Exception");
System.out.println(e.getMessage());
}finally{
// Actual contact insertion will happen at this step
System.out.println("the finally block");
session.flush();
session.close();
System.out.println("out of finally");
}

HIBNERNATE CFG:

<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@10.20.169.171:1521:CFSDEV </property>
<property name="hibernate.connection.username">Cfs_sas</property>
<property name="hibernate.connection.password">cfs123</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect"> org.hibernate.dialect.OracleDialect </property>

<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="contact.hbm.xml"/>

Posted by Sanket on Wednesday, 09.24.08 @ 16:52pm | #80660

when i was executing the code iam geting following Exception in thread "main" java.lang.NullPointerException
at roseindia.tutorial.hibernate.FirstExample.main(FirstExample.java:42)
any one plz help

Posted by sreekumar on Friday, 09.19.08 @ 13:13pm | #80482

hi when i am running this example then i am getting nullpointer exception like "Exception in thread "main" java.lang.NullPointerException" ..please anyone help me

Posted by preeti on Monday, 09.15.08 @ 14:44pm | #79553

i need more basic examples programs on hibernate.

Posted by naveen on Saturday, 09.13.08 @ 12:28pm | #79090

it is good but tell me more details of the each and every line of the first xml codind

Posted by eswar on Thursday, 09.11.08 @ 11:20am | #78647

Hi,
I am trying run the firstexample of hybernate.I got the follwing problems.

<property name="firstName">
<column name="FIRSTNAME"/>
</property>

If i use the above code in the xml,
i got

The content of element type "property" must match "null"

Here, when i remove the column tag only, the error will disapper.

When i run the program,

org.hibernate.mappingException : could not read mappings from resource- contact.hbm.xml..

Please help me..

Posted by Kiran on Friday, 09.5.08 @ 15:11pm | #77247

Im runing this example in my struts application ..,

when it reach this line , im getting nullpointer exception ..,
pls help me out of this..

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

[8/12/08 13:55:48:266 IST] 65502792 RequestProces W org.apache.struts.action.RequestProcessor Unhandled Exception thrown: class java.lang.NullPointerException
[8/12/08 13:55:49:234 IST] 65502792 WebGroup E SRVE0026E: [Servlet Error]-[]: java.lang.NullPointerException

Thanks
Mani

Posted by Mani on Tuesday, 08.12.08 @ 14:05pm | #72478

Hibernate: insert into MyBook (bookName, bookAuthor, bookId) values (?, ?, ?)
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Option type out of range

what does it mean?

Posted by kk on Tuesday, 07.15.08 @ 11:47am | #67345

Make slight modification to code to insert data into DB.Otherwise it will only be in session.

In FirstExample.java

Contact contact = new Contact();
contact.setId(3);
contact.setFirstName("Deepak");
contact.setLastName("Kumar");
contact.setEmail("deepak_38@yahoo.com");
Transaction tx = session.beginTransaction();
session.save(contact);
tx.commit();
System.out.println("Done");

In contact.hbm.xml change class "assigned" to "increment"

<id name="id" type="long" column="ID" >
<generator class="increment"/>
</id>

Posted by Sanjiv bhargava on Thursday, 06.12.08 @ 19:26pm | #63125

what to write in the Driver name if we are using Oracle database

Posted by naresh on Wednesday, 06.11.08 @ 10:47am | #62998

hell sir
when i am executing the FirstExample in struts
it is showing nullpointer exception..can you give the solution for this..

Posted by suresh on Wednesday, 05.28.08 @ 14:20pm | #61264

hi.... I use the above code to run my project but it showed me following error: log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly. entity class not found: Student But the Student class is present. Even i did mapping in hibernate.cfg.xml The Person.hbm.xml file is: <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated May 12, 2008 11:13:52 AM by Hibernate Tools 3.2.1.GA --> <hibernate-mapping> <class name="Person" table="person" catalog="test"> <id name="personId" type="int"> <column name="personId" /> <generator class="assigned" /> </id> </class> </hibernate-mapping> and the Student.hbm.xml file is: <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated May 12, 2008 11:13:52 AM by Hibernate Tools 3.2.1.GA --> <hibernate-mapping> <class name="Student" table="student" catalog="test"> <id name="studentId" type="int"> <column name="studentId" /> <generator class="assigned" /> </id> <property name="studentName" type="string"> <column name="studentName" length="20" /> </property> <property name="studentAge" type="java.lang.Integer"> <column name="studentAge" /> </property> <property name="personId" type="java.lang.Integer"> <column name="personId" /> </property> </class> </hibernate-mapping>

Posted by Anita on Monday, 05.12.08 @ 22:57pm | #59515

If you r a beginer then plz do not forget to add c:\hibernate-3.2\lib\*.jar files to your class path variable.
Otherwise Main method will how errors.

Posted by Amit Ruhil on Sunday, 04.27.08 @ 21:19pm | #58002

While i am running the FirstExample.java file runas javaApplication it is showing
Dialect class not found:
java.lang.NullPointerException
at src.com.FirstExample.main(FirstExample.java:29)
Exception in thread "main"

Error.so how can i solve this. Can anyone needful to me..

Posted by Naveen on Wednesday, 04.23.08 @ 18:36pm | #57704


I am able to run the application with the help of this article using orcle11g database..

And also i found the same article with more details on the below given link.

http://www.javajazzup.com/issue6/page34.shtml

Thanks for the article.

Posted by ssmnaidu on Thursday, 04.10.08 @ 23:26pm | #55862

Hi,
Based on the example given , I'm trying to run my application using Hibernate 2.1. But I'm getting exception net.sf.hibernate.MappingException : Error reading Resource Employee.hbm.xml.

I have my hibernate.cfg.xml and Employee.hbm.xml in project/bin/ folder as suggested.

My Employee.hbm.xml is as follows
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping SYSTEM "Sun/Workspace/HibernateExample/Sun/Workspace/HibernateExample/hibernate-mapping-2.0.dtd" >
<hibernate-mapping>
<class name="com.hibernate.Employee" table="Employee">
<id name="empID" type="Integer" column="EmpID">
<generator class="assigned"></generator>
</id>
<property name="dob">
<column name="DOB"/>
</property>
<property name="empName">
<column name="EmpName"/>
</property>
<property name="salary">
<column name="Salary"/>
</property>
</class>
</hibernate-mapping>

and my hibernate.cfg.xml is as follows
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
<hibernate-configuration>
<session-factory name="MyFactory">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/MySQL</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>

Please do guide me in getting this resolved.

Posted by Ravi on Monday, 03.31.08 @ 08:21am | #54848

hi

i'm trying to do the firstexample of hybernate.but i'm recieving the message as follows

Inserting Record
Hibernate: insert into CONTACT (FNAME, LNAME, EMAIL) values (?, ?, ?)
Done


data is not inserted in to record..and no error or exceptin message

Posted by Dhanushka Jayathilaka on Tuesday, 03.18.08 @ 18:23pm | #53198

Hello RoseIndia Team / Deepak Kumar,

Please include begin transaction and commit transaction statements in FirstExample.java to save the data in the database.
---------------------------------------------
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session=sessionFactory.openSession();
Transaction tx=session.beginTransaction();//This line is Missing in the example.

session.save(contact);
tx.commit();//Missing in the example.
----------------------------------------------

As per the example the datas doesn't get save in the database and beginners have to struggle a lot.
I hope you will do the needful ASAP.
Thank you,
Suraj Gupta

Posted by Suraj Gupta on Tuesday, 03.18.08 @ 17:09pm | #53185

init:
deps-jar:
Compiling 1 source file to D:\java\HibernateDemo\build\classes
compile:
run:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Inserting Record

Hibernate: insert into CONTACT (FIRSTNAME, LASTNAME, EMAIL, ID) values (?, ?, ?, ?)
Done
BUILD SUCCESSFUL (total time: 2 seconds)

************************************************
why this message is coming? Evenif the record was inserted.

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


Posted by tapan on Tuesday, 03.11.08 @ 18:05pm | #52305

Hi,

I am trying out these examples and using in my code but the session.save(object) does not insert the object in the DB.Am not getting any errors or exceptions here is a snippet of the console stdout :
********insert Start for test********8
generated identifier: 1, using strategy: org.hibernate.id.Assigned
insert Test Done
processing flush-time cascades
dirty checking collections
Flushed: 1 insertions, 0 updates, 0 deletions to 1 objects
Flushed: 0 (re)creations, 0 updates, 0 removals to 0 collections
listing entities:
com.directv.ei.hibernate.pojos.hqltest{name=Auntora, id=1}
about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
opening JDBC connection
insert into HQLTEST (NAME, ID) values (?, ?)
Hibernate: insert into HQLTEST (NAME, ID) values (?, ?)
Executing batch size: 1
success of batch update unknown: 0
about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]
aggressively releasing JDBC connection
----------------------------------------------********insert Start for test********8
generated identifier: 1, using strategy: org.hibernate.id.Assigned
insert Test Done
processing flush-time cascades
dirty checking collections
Flushed: 1 insertions, 0 updates, 0 deletions to 1 objects
Flushed: 0 (re)creations, 0 updates, 0 removals to 0 collections
listing entities:
com.directv.ei.hibernate.pojos.hqltest{name=Auntora, id=1}
about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
opening JDBC connection
insert into HQLTEST (NAME, ID) values (?, ?)
Hibernate: insert into HQLTEST (NAME, ID) values (?, ?)
Executing batch size: 1
success of batch update unknown: 0
about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]
aggressively releasing JDBC connection
----------------------------------------------********insert Start for test********8
generated identifier: 1, using strategy: org.hibernate.id.Assigned
insert Test Done
processing flush-time cascades
dirty checking collections
Flushed: 1 insertions, 0 updates, 0 deletions to 1 objects
Flushed: 0 (re)creations, 0 updates, 0 removals to 0 collections
listing entities:
com.directv.ei.hibernate.pojos.hqltest{name=Test, id=1}
about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
opening JDBC connection
insert into HQLTEST (NAME, ID) values (?, ?)
Hibernate: insert into HQLTEST (NAME, ID) values (?, ?)
Executing batch size: 1
success of batch update unknown: 0
about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]
aggressively releasing JDBC connection
----------------------------------------------

Can anyone help.......

Posted by a on Tuesday, 03.4.08 @ 05:15am | #51234

By commiting ur transaction ur problem may be solved

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session=sessionFactory.openSession();
Transaction tx=session.beginTransaction();

System.out.println("Inserting Record");
Contact contact=new Contact();

contact.setFirstName("Deepak");
contact.setLastName("kumar");
contact.setEmail("pra@yahoo.com");
contact.setId(3);
session.save(contact);
System.out.println("Done");
tx.commit();

Posted by prabhu on Saturday, 02.23.08 @ 15:47pm | #49662

When is better place to close a session?. I mean, if I've a UserManager class, and I've:

getById
getByName
...

Is convenient that I open a session for all methods into the constructor or open (and close) a session in each method?

Best regards.

Juan Pablo.

Posted by juan pablo on Thursday, 02.21.08 @ 00:12am | #49250

Hi,
I receive the following error:
Resource: ro/isd/db/t1.hbm.xml not found

t1.hbm.xml is in same package as t1.java

Please, help.

Posted by iulian on Wednesday, 02.20.08 @ 20:17pm | #49229

While Iam running the First Example..I am getting NullPointer Exception...Any one can help me in Ths Regards...
Thanks In Advance..
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

System.out.println("222222222222222");
session =sessionFactory.openSession();
System.out.println("3333333333");
//Create new instance of Contact and set values in it by reading them from form object
Transaction tx=session.beginTransaction();
System.out.println("Inserting Record");
Contact contact = new Contact();
contact.setId(6);
contact.setFirstName("Satya");
contact.setLastName("Soft");
contact.setEmail("satyasoft@gmail.com");
session.save(contact);
System.out.println("Done");

Posted by Satyanarayana.n on Saturday, 02.16.08 @ 19:45pm | #48617

how to retrive data from a database

Posted by hhh on Saturday, 01.19.08 @ 18:41pm | #45597

Hi all.
i m new with hibernet.......when i m trying to run my first application i m getting following exceptio.
Exception in thread "main" java.lang.NullPointerException
at com.FirstExample.main(FirstExample.java:33).

Posted by sapna on Wednesday, 01.16.08 @ 15:38pm | #45349

i am using Microsoft SQL Server. and i m getting a error that
JDBC Driver class not found: com.microsoft.jdbc.sqlserver.SQLServerDriver.
can anybody help me out

Posted by Anup on Saturday, 01.12.08 @ 21:16pm | #45059

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

but data is not updating or inserting or updating into data base

Posted by anand on Thursday, 01.10.08 @ 10:10am | #44885

Hi,
I am new to hibernate concept,
i did this example .but
DATA IS NOT UPDATING IN database,

I have the same problem

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Inserting Record
Done
Hibernate: insert into CONTACT (FIRSTNAME, LASTNAME, EMAIL, ID) values (?, ?, ?, ?)

but data is not updating or inserting or updating into data base

table has been created.but data's are not updating. Where i need to do the modification.

Thanks in advance.
sam.R
+919902199334

Posted by sam on Thursday, 01.3.08 @ 09:59am | #44414

i ahve java,mysql,hibernate on my machine..

i have defined class structure..
have defined xml mapping..
have created hibernate.cfg.xml
have created corresponding database

now my manager is asking to create class object n then store it in DB..but i dont have either apache ant or eclipse (or something else)..

is it possible..can u help me..waiting for ur reply..
:)

Posted by gunjan on Thursday, 12.20.07 @ 15:17pm | #43100

This might be a good article if there weren't annoying ads sitting in front of the text.

What is the point of a site that can't be read????

Posted by matt on Tuesday, 12.18.07 @ 21:16pm | #42855

If you get log4j error written below:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
/hibernate.cfg.xml not found

Please add log4j.properties in the project, your problem will be solved.

Posted by Sudhir Tewatia on Friday, 12.14.07 @ 14:12pm | #42229

hi all.
i m new with hibernet.......when i m trying to run my first application i m getting following exceptio.
Exception in thread "main" java.lang.NullPointerException
at com.FirstExample.main(FirstExample.java:33).
i have deployed all the jar files properly........but why i m getting such problem...........plz reply me.........thanx
kamlesh

Posted by kamlesh Rewapati on Friday, 12.7.07 @ 02:01am | #41478

i am new to hibernate so whats ur advice .... what are the thinks that i hav to know before starting hibernate ..which IDE supports hibernate .. pls advice.......

Posted by rajanish on Thursday, 12.6.07 @ 19:58pm | #41461

when i run the program i am getting java.lang.noclassdeffound error and exception in thread main.please tell how to solve the promblem

Posted by sagar on Friday, 11.23.07 @ 12:16pm | #38617

test

Posted by test on Tuesday, 11.20.07 @ 11:19am | #37926

Why we are using sessionFactory,Session concepts in hybernet?

Posted by jahnavi on Saturday, 11.17.07 @ 12:06pm | #37611

DATA IS NOT UPDATING IN database,

I have the same problem

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Inserting Record
Done
Hibernate: insert into CONTACT (FIRSTNAME, LASTNAME, EMAIL, ID) values (?, ?, ?, ?)

but data is not updating or inserting or updating into data base

Posted by Jagg on Tuesday, 11.6.07 @ 02:36am | #35730

In test.java please commit to data base which will be stored in contact
Transaction tx=session.beginTransaction();
session.save(contact);
tx.commit();

Posted by ram on Monday, 11.5.07 @ 23:29pm | #35691

you need log4j.properties file to be included to get rid of the log4j warnings....the code works fine.....

Posted by jitttu on Thursday, 11.1.07 @ 05:32am | #35295

Data is not inserting to database

Posted by divya on Tuesday, 10.30.07 @ 22:32pm | #35186

Hi i m trying ur FirstExample
But I m getting NumberFormatException

java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at org.hibernate.util.PropertiesHelper.getInt(PropertiesHelper.java:23)
at org.hibernate.connection.DriverManagerConnectionProvider.configure(DriverManagerConnectionProvider.java:40)
at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:80)
at org.hibernate.cfg.SettingsFactory.createConnectionProvider(SettingsFactory.java:301)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:111)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:1497)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1041)
at roseindia.tutorial.hibernate.FirstExample.main(FirstExample.java:25)
For input string: ""


Please tell me what to do?

thanks...


Posted by pradnya on Monday, 10.29.07 @ 16:52pm | #35065

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
/hibernate.cfg.xml not found
org.hibernate.HibernateException: /hibernate.cfg.xml not found
at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:147)
at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1287)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1309)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1296)
at roseindia.tutorial.hibernate.FirstExample.main(FirstExample.java:19)
Exception in thread "main" java.lang.NullPointerException
at roseindia.tutorial.hibernate.FirstExample.main(FirstExample.java:35)

Posted by G on Monday, 10.29.07 @ 13:20pm | #35055

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Inserting Record
Done
Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Cannot open connection
at org.hibernate.exception.ErrorCodeConverter.convert(ErrorCodeConverter.java:67)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
at org.hibernate.jdbc.AbstractBatcher.openConnection(AbstractBatcher.java:384)
at org.hibernate.jdbc.JDBCContext.connect(JDBCContext.java:141)
at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:88)
at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:73)
at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:66)
at org.hibernate.jdbc.AbstractBatcher.prepareBatchStatement(AbstractBatcher.java:130)
at org.hibernate.persister.entity.BasicEntityPersister.insert(BasicEntityPersister.java:1809)
at org.hibernate.persister.entity.BasicEntityPersister.insert(BasicEntityPersister.java:2171)
at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:46)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:239)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:223)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:136)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:274)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:669)
at roseindia.tutorial.hibernate.FirstExample.main(FirstExample.java:36)
Caused by: java.sql.SQLException: Syntax error or access violation message from server: "Unknown database 'hibernatetutorial'"
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:1997)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:1906)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:2520)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:817)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:1786)
at com.mysql.jdbc.Connection.<init>(Connection.java:450)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:411)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
at org.hibernate.jdbc.AbstractBatcher.openConnection(AbstractBatcher.java:381)
... 15 more

Posted by sanju on Wednesday, 10.24.07 @ 14:43pm | #34669

Hi,

I have created one application using hibernate with HSQL. I wanted to change it to MySQL. When I have changed my Hibernate.properties file but after changing the file i get the following error.

HTTP ERROR: 503
SERVICE_UNAVAILABLE
RequestURI=/

Powered by jetty://


pls help me asap..

Thanks in Advance.
Swapnil P.Patil.

Posted by Swapnil on Friday, 10.19.07 @ 13:16pm | #34386

Hi,

i am, getting log4j errors when i am running above code could any body let me know why warning displaying.i am pasting those warnings here.

log4j: no appenders could be found for logger(org.hibernate.cfg.environment)
log4j: please initialize log4j system properly.

Posted by subrahmanyam on Wednesday, 10.10.07 @ 19:56pm | #33015

Hello,
I am using NetBeans IDE and while I was trying to run the above code, I got the following error.
-------------------------------------------------
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Could not parse configuration: /hibernate.cfg.xml
---------------------------------------------------
I am new to hibernate and don't know why this has occurred. I think it must not be able to parse the xml configuration file. Can anyone help me.

Posted by srs on Tuesday, 10.9.07 @ 11:46am | #32610

this example, inserting data with wornings log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.

Posted by Alok Mishra on Thursday, 10.4.07 @ 14:38pm | #31361

Hi i am using sql server database and i am getting this output

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Inserting Record
Done
Hibernate: insert into CONTACT (FIRSTNAME, LASTNAME, EMAIL, ID) values (?, ?, ?, ?)

but data is not updating or inserting or updating into data base

Posted by SHAMEMA on Sunday, 09.30.07 @ 14:44pm | #30501

Hi,

i am trying standalone hibernate program,while excuting org.hibernate.cfg.Configuarion =new Configuration(); giving following error.

Please any one can help me ASAP.


Exception in thread "main" java.lang.ExceptionInInitializerError
at com.hibernate.client.BookInsertion.main(BookInsertion.java:21)
Caused by: org.apache.commons.logging.LogConfigurationException: org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused by java.lang.NullPointerException) (Caused by org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused by java.lang.NullPointerException))
at org.apache.commons.logging.impl.LogFactoryImpl.newInstance(LogFactoryImpl.java:543)
at org.apache.commons.logging.impl.LogFactoryImpl.getInstance(LogFactoryImpl.java:235)
at org.apache.commons.logging.impl.LogFactoryImpl.getInstance(LogFactoryImpl.java:209)
at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:351)
at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:110)
... 1 more
Caused by: org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused by java.lang.NullPointerException)
at org.apache.commons.logging.impl.LogFactoryImpl.getLogConstructor(LogFactoryImpl.java:397)
at org.apache.commons.logging.impl.LogFactoryImpl.newInstance(LogFactoryImpl.java:529)
... 5 more
Caused by: java.lang.NullPointerException
at org.apache.commons.logging.impl.LogFactoryImpl.getLogConstructor(LogFactoryImpl.java:374)
... 6 more

Posted by Padeep on Wednesday, 09.26.07 @ 16:07pm | #29712

It seems the guy who wrote this never tested it actually.

Without the Transaction tx = session.beginTransaction() and tx.commit(), you will never get a row inserted into the db. If you give that, everything works fine....

To yolan,

U have to create a database like this.
create database hibernatetutorial;
use hibernatetutorial;
then create the table.
then execute the program. It will work...

Posted by Krishna Kumar on Wednesday, 09.26.07 @ 15:18pm | #29645

hi there is problem with url string which u r entering
so let me know whic db u r using and db server m/c ip

Posted by Rahul on Saturday, 09.15.07 @ 12:05pm | #27016

Hi i am using sql server database and i am getting this output

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Inserting Record
Done
Hibernate: insert into CONTACT (FIRSTNAME, LASTNAME, EMAIL, ID) values (?, ?, ?, ?)

but data is not updating or inserting or updating into data base

Posted by Rahul on Saturday, 09.15.07 @ 11:53am | #27015

i like the basic help and your way of Explenetion With Example.
It helps me

Posted by Ritesh on Friday, 09.14.07 @ 10:42am | #26952

Hi,

I am getting the below exception while running the program. The table structure is created though but no data is getting inserted to the table and then the exception.



Hibernate: insert into CONTACT (FIRSTNAME, LASTNAME, EMAIL, ID) values (?, ?, ?, ?)
org.hibernate.jdbc.BatchedTooManyRowsAffectedException: Batch update returned unexpected row count from update [0]; actual row count: 7810893; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:71)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:46)
at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:68)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:246)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:237)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at FirstExample.main(FirstExample.java:33)

If anyone has come across this type of exception. Pls help..

Thanks in advance!
Sunny

Posted by Sunny on Thursday, 09.13.07 @ 22:27pm | #26930

I figured out the problem in FirstExample.java why it is not inserting into the database.
The problem is there is no demarcation of Transaction.

Please add following code appropriately.
org.hibernate.Transaction tx = session.beginTransaction();
//ALL the code

tx.commit();

Posted by Prashant on Friday, 09.7.07 @ 07:16am | #26266

I am also facing the same problem as Parvesh. The database is built with all the tables but Contact data is not getting inserted. Also there is no error. Can somebody help us?

Thanks

Posted by Prashant on Friday, 09.7.07 @ 06:51am | #26216

Hi,

When I am trying to run this application.

I am getting NullPointer Exception.

Please give me the feedback.

Regards,
Sundararaman.V.S.

Posted by Vidyasankar Sundararaman on Thursday, 09.6.07 @ 15:48pm | #25285

Can i create an new schema(table) in my database using Hibernate provided i have my POJOs and mappings ready?

Posted by Divya on Thursday, 09.6.07 @ 11:17am | #25190

first example running best but data which I insert not found in the database although the table structure is build. Means shows table but with out any data. The console output is same as you shown

Posted by parvesh on Thursday, 08.30.07 @ 12:45pm | #24493

when running the hibernet programe iam getting the NullPointer Exception.so please tell me why iam getting the exception.

Posted by sreenivas on Monday, 08.27.07 @ 17:05pm | #24253

here Session is Hibernate Session so
//SessionFactory sessionFactory = ((Object)new Configuration()).configure().buildSessionFactory();
Object SessionFactory;
session = ((Object)SessionFactory).openSession();


above lines of code is wrong as 'openSession is method of Hibernates Sesion not of Object's method.

So in place of above place the following code :
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();

Posted by Pawan on Thursday, 08.23.07 @ 17:29pm | #23983

hello, I'm trying to use hte source code that is given, but then I got error

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Inserting Record
Done
Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Cannot open connection
.......
Caused by: java.sql.SQLException: Syntax error or access violation message from server: "Unknown database 'hibernatetutorial'"
.......

please tell me what should I do?thank you

Posted by yolan on Monday, 08.13.07 @ 11:09am | #23270

This site is very useful.

Right now i am looking for an Example on Hibernate+Spring, which will intract with Portals, which run inside Portal server, can any one help in in this issue.

I want to develop an Basic application , which takes some input from user, and stores it in sql server database, and I need to use spring+hibernate in that.

Posted by Hanumantha Rao on Thursday, 08.2.07 @ 16:24pm | #22490

Hi , you must be inserting the same value in the column which is primary key.

Posted by Balakrishna on Thursday, 08.2.07 @ 10:27am | #22469

This document is very useful

Posted by mohan on Wednesday, 07.25.07 @ 03:33am | #21872

problem occuring while parsing mapping file

Posted by PAVAn on Sunday, 07.22.07 @ 14:06pm | #21733

Hi I went through this tutorial but i am getting one error which is compilation error: please tell me why is it?

I changed some code like this in FirstExample.java :
==========================================

package net.roseindia.tutorial.hibernate;
import org.hibernate.*;
import javax.security.auth.login.*;

//import roseindia.tutorial.hibernate.*;

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
//SessionFactory sessionFactory = ((Object)new Configuration()).configure().buildSessionFactory();
Object SessionFactory;
session = ((Object)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(6);
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();
}
}
}


I am getting error :

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method openSession() is undefined for the type Object

at net.roseindia.tutorial.hibernate.FirstExample.main(FirstExample.java:18)


Please help me to solve the problem....

Posted by Gajanan K Bandale on Thursday, 07.19.07 @ 15:46pm | #21568

I got the list from hql query.Now how can i print the value of each row of the table from the list object.If any one has the solution pls mail me.

Posted by Suresh kumar on Wednesday, 07.11.07 @ 15:16pm | #21082

log4j:WARN No appenders could be found for logger (roseindia.tutorial.hibernate.HibernateUtil).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" java.lang.ExceptionInInitializerError
at roseindia.tutorial.hibernate.HibernateUtil.<clinit>(HibernateUtil.java:29)
at roseindia.tutorial.hibernate.FirstExample.main(FirstExample.java:23)
Caused by: java.lang.NoClassDefFoundError: org/dom4j/DocumentException
at roseindia.tutorial.hibernate.HibernateUtil.<clinit>(HibernateUtil.java:24)
... 1 more

Posted by shiva on Wednesday, 07.11.07 @ 12:35pm | #21068

exceeption while inserting the record into DB on hibernate. i am getting the following exception

can anyone plz help me, thanks

Hibernate: insert into events (name, amount, desc, id) values (?, ?, ?, ?)
org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch update
at org.hibernate.exception.ErrorCodeConverter.convert(ErrorCodeConverter.java:70)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:179)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:226)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:136)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:274)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:726)
at src.com.EventMain.main(EventMain.java:35)
Caused by: java.sql.BatchUpdateException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc, id) values ('chowdary', null, null, 0)' at line 1
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1093)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:851)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:57)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:172)
... 6 more
Exception in thread "main"

Posted by praveen on Tuesday, 07.10.07 @ 14:59pm | #21025

og4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.

Posted by shanth on Saturday, 07.7.07 @ 11:45am | #20871

am connecting to Mysql.its showing but the record is not getting inserted.
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Inserting Record
Hibernate: insert into CONTACT (FIRSTNAME, LASTNAME, EMAIL, ID) values (?, ?, ?, ?)
Done

Posted by jijo on Tuesday, 06.26.07 @ 11:29am | #20203

I am connecting to Mysql.its showing but the record is not getting inserted.
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Inserting Record
Done
Hibernate: insert into CONTACT (FIRSTNAME, LASTNAME, EMAIL, ID) values (?, ?, ?, ?)

Posted by jijo on Tuesday, 06.26.07 @ 11:25am | #20201

instead of "net.sf.hibernate.dialect.Oracle9Dialect" use "org.hibernate.dialect.MySQLDialect"..

Posted by soma on Monday, 06.25.07 @ 15:43pm | #20148

Hi I am getting the following error can anybody help.

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
java.lang.NullPointerException
at roseindia.tutorial.hibernate.FirstExample.main(FirstExample.java:40)
Dialect class not found: net.sf.hibernate.dialect.Oracle9Dialect
Exception in thread "main"

hibernate.cfg.xml
------------------
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
<property name="hibernate.connection.username">scott</property>
<property name="hibernate.connection.password">tiger</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">net.sf.hibernate.dialect.Oracle9Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>

contact.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="roseindia.tutorial.hibernate.Contact" table="CONTACT">
<id name="id" type="long" column="ID" >
<generator class="assigned"/>
</id>

<property name="firstName">
<column name="FIRSTNAME" />
</property>
<property name="lastName">
<column name="LASTNAME"/>
</property>
<property name="email">
<column name="EMAIL"/>
</property>
</class>
</hibernate-mapping>

Contact.java
------------------
package roseindia.tutorial.hibernate;

/**
* @author Deepak Kumar
*
* Java Class to map to the datbase Contact Table
*/
public class Contact {
private String firstName;
private String lastName;
private String email;
private long id;

/**
* @return Email
*/
public String getEmail() {
return email;
}

/**
* @return First Name
*/
public String getFirstName() {
return firstName;
}

/**
* @return Last name
*/
public String getLastName() {
return lastName;
}

/**
* @param string Sets the Email
*/
public void setEmail(String string) {
email = string;
}

/**
* @param string Sets the First Name
*/
public void setFirstName(String string) {
firstName = string;
}

/**
* @param string sets the Last Name
*/
public void setLastName(String string) {
lastName = string;
}

/**
* @return ID Returns ID
*/
public long getId() {
return id;
}

/**
* @param l Sets the ID
*/
public void setId(long l) {
id = l;
}

}


FirstExample.java
-----------------------
package roseindia.tutorial.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.Transaction;
import java.sql.SQLException;
/**
* @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
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
Transaction tx=session.beginTransaction();
//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);
tx.commit();
System.out.println("Done");
}catch(Exception e){
System.out.println(e.getMessage());


}finally{
// Actual contact insertion will happen at this step
session.flush();
try{
session.connection().commit();
}
catch(SQLException e)
{
System.out.println(e.getMessage()) ;
}

session.close();

}

}
}





Posted by MIthun on Thursday, 06.21.07 @ 11:19am | #19849

while I'm trying to get the session in the Hibernateprogram by using the below statement I'm executing this program in NetBeans5.0 and using the databaseserver is MySql4.1

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

it is giving that Exception in thread "main" java.lang.NullPointerException

I'm not able to connect to hibernate.cfg.xml this file and also tell me where can i place these(hibernate.cfg.xml and hibernate.hbm.xml) files in NetBeans5.0

please can u any body helpme regarding this problem

Posted by Gandhi on Wednesday, 06.13.07 @ 12:48pm | #19095

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" java.lang.NullPointerException
at kalyan.hibernate.FirstExample.main(FirstExample.java:39)
Could not parse mapping document from resource contact.hbm.xml

Posted by kalyan on Saturday, 06.9.07 @ 21:44pm | #18745

Cannot open connection
Cannot open connection
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.

Posted by rajesh on Tuesday, 06.5.07 @ 13:42pm | #18268

This page is very useful.

Posted by Kanagasabapathi Palanisamy on Friday, 06.1.07 @ 22:58pm | #17968

I think that the following 2 lines are needed to insert the data into the database.

<b>Transaction tx=session.beginTransaction();</b>

Contact contact = new Contact();
contact.setId(3);
...
session.save(contact);

<b>tx.commit();</b>

Posted by fresh on Thursday, 05.31.07 @ 19:58pm | #17873

i think you need to place log.properties file application root directory.
i resolved this by doing same thing

Posted by imtiyaz on Tuesday, 05.29.07 @ 15:51pm | #17644

I am connecting to Oracle.its showing but the record is not getting inserted.
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Inserting Record
Hibernate: insert into CONTACT (FIRSTNAME, LASTNAME, EMAIL, ID) values (?, ?, ?, ?)
Done

Posted by Vijay on Monday, 05.28.07 @ 16:21pm | #17535

I am getting the following error message when i execute this program in eclipse.
I am not aware where to put the hibernate.cfg.xml file

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
/hibernate.cfg.xml not found
Exception in thread "main" java.lang.NullPointerException
at com.gm.efecs.em.cg.HibernateExample.main(HibernateExample.java:39)

Posted by Nalini on Thursday, 05.24.07 @ 13:03pm | #17142

Hi,

Since Hibernate is a persistence tool. It performs the operation in transactinal environment. Inorder to work the above code should me modified as.

try{
// This step will read hibernate.cfg.xml and prepare hibernate for use
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
Transaction tx=session.beginTransaction();
//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);
tx.commit();
System.out.println("Done");
}catch(Exception e){
System.out.println(e.getMessage());


Posted by Srinivas on Wednesday, 05.23.07 @ 16:44pm | #17092

Hi Chris,
Thanks a lot for your suggestion.It did work!!! Still not sure, why we need to flush and then commit the connection.

Posted by Anand Kishore on Wednesday, 05.16.07 @ 17:44pm | #16150

hi,
When i try to run this example i am getting the following error
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Could not parse mapping document from resource contact.hbm.xml

Posted by gayathri on Wednesday, 05.16.07 @ 12:47pm | #16118

to make this work you need to commit after the flush.

session.connection().commit();

works fine after that.

c.

Posted by Chris Schulz on Friday, 05.11.07 @ 11:53am | #15635

Hi,

I have the same problem as Anand. I extracted the sample app, set the config etc... the app runs fine with no exceptions... the table is created but no record is inserted. any ideas?

win xp, my sql 5, eclipse 3.2, java 1.5

cheers.

Posted by Chris Schulz on Friday, 05.11.07 @ 05:52am | #15625

Hi,
I am trying the same tutorial as suggested and also the program (FirstExample.java) is running in eclipse IDE without any errors.It is also showing the output as given in tutorial. But when i check the values in the mysql database, the values are not inserted in the mysql database. Please provide solution for it.

Posted by Tester on Friday, 05.4.07 @ 21:01pm | #15278

Hi, i got following error message when i executed simple java application.

WARNING: No connection properties specified - the user must supply JDBC connections
Exception in thread "main" org.hibernate.HibernateException: Hibernate Dialect must be explicitly set
at org.hibernate.dialect.DialectFactory.determineDialect(DialectFactory.java:57)

The content of hibernate-cfg.xml is #

<session-factory>
<property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="hibernate.connection.url">jdbc:hsqldb:hsql://localhost:9001/xdb</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="Track.hbm.xml"/>
</session-factory>

I am unable to find any error in the above xml. Please suggest me how to solve this.

Regards,
Raghav

Posted by raghavendar on Friday, 05.4.07 @ 15:42pm | #15264

Excellent.

Very simple way of explaing how to configure the hibernate.

good one..

Posted by Shalem Merugolu on Wednesday, 05.2.07 @ 13:09pm | #15161

I am working MySQL Server and Hibernate as suggested in the example.After executing the client to insert a record neither do I get any exception nor does the data gets inserted into the contact table.Wondering where the data is going ???

Posted by Anand Kishroe on Thursday, 04.26.07 @ 11:43am | #14954

Regarding Arun,

make sure you have these jar files added to avoid errors..

commons-collections/3.2/commons-collections-3.2.jar
dom4j/1.6/dom4j-1.6.jar
log4j/1.2.11/log4j-1.2.11.jar
postgresql/8.1-404.jdbc3/postgresql-8.1-404.jdbc3.jar
hibernate/3.1.2/hibernate-3.1.2.jar
commons-logging/1.0.4/commons-logging-1.0.4.jar
cglib/2.1.3/cglib-2.1.3.jar
asm/1.5.3/asm-1.5.3.jar
jta/1.0.1B/jta-1.0.1B.jar

Posted by new guy on Saturday, 04.14.07 @ 00:55am | #14128

Great tutorials!

Thanks so much!

Posted by Lucise on Tuesday, 04.10.07 @ 08:05am | #13689

when i try to run this im getting this error
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" java.lang.NoClassDefFoundError: net/sf/ehcache/CacheException
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at org.hibernate.cfg.SettingsFactory.createCacheProvider(SettingsFactory.java:327)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:219)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:1881)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1174)
at roseindia.tutorial.hibernate.FirstExample.main(FirstExample.java:21)

Posted by Arun on Monday, 04.9.07 @ 12:58pm | #13627

hi all,this is one of the site to learn,which included here step by step.


thanks
naidu

Posted by naidu annamaneni on Thursday, 03.29.07 @ 13:28pm | #12902

One of the best places to learn about almost anything in a fast and simple manner. I have been referring to this site so often and a great tool to help yourself to get into the race immediately.
Thanks all

Posted by ash on Wednesday, 03.21.07 @ 12:00pm | #12330

I have exeption nullpoint in line
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
I brocked line to 2 lines
Configuration conf = new Configuration();
SessionFactory sessionFactory = conf.configure().buildSessionFactory();
end exeption cam in 1 line
pls help me Thanks.

Posted by dima on Wednesday, 03.14.07 @ 16:35pm | #11689

I could insert the records into dbase, with out using the transaction.commit().
Any reason for this to happen .

Please can you let meknow..

thanks,
Srini

Posted by Srini on Sunday, 03.11.07 @ 05:33am | #11349

this tutorial helps me to understand about hibernate.

Posted by shyama on Saturday, 03.10.07 @ 07:04am | #11294

Hi, really this is site is very useful not for the biggners also for the experience people....I am trying to develop a small appliaction in hibernate.jsut to show the contents of the tables thru class..but i am facing following errors anybody can help me...log4j:WARN No appenders could be found for logger (com.src.TestMehjong).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.HibernateException: No CurrentSessionContext configured!
at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:506)
at com.src.TestMehjong.listTable(TestMehjong.java:44)
at com.src.TestMehjong.main(TestMehjong.java:36)

Posted by Durgesh on Friday, 03.9.07 @ 11:34am | #11225

Good job done!!
Its really usefull n interesting!!!
Pretty simple to understand also!!

Posted by Priyanka on Wednesday, 02.28.07 @ 12:53pm | #9937

I am new to hibernates, I would like to know directory structure of deploying and placing xml and java classes. Also to compile them as step by step process. please help me

Posted by Mamatha on Tuesday, 02.27.07 @ 12:33pm | #9805

hi all,
this is one of the tutorial which ll guide u in an efficient manner for those who want to excel in Hibernate...it gives u the very basic knowledge of what hibernate is....so a good foundation for ur skill

regards
Suma Manohar Humberi

Posted by Suma Manohar Humberi on Tuesday, 02.27.07 @ 10:34am | #9791

Good tutorial for beginners.

Thanks,
Sandeep

Posted by Sandeep Bisani on Saturday, 02.24.07 @ 21:47pm | #9479

Show us the steps not the code , we beginners want the steps not the code . This document is not formatted and misguide us . We need simple steps .

If anybody can help , please help me ..

Thanks

Posted by Rahul on Saturday, 02.24.07 @ 12:01pm | #9429

This is a terrific tutorial and much better than any book I can buy. It helped me a lot with my work. May you always be able to write great lessions like this!

Posted by Larry on Tuesday, 02.20.07 @ 18:50pm | #8516

hi

this is very good website to beginer and
thank you verymuch for website people and staff

ok bye hava a nice day

Posted by rama on Thursday, 02.15.07 @ 22:07pm | #7992

As a beginner to hibernate technology, I find this tutorial very useful . Initially I faced some problems while running the application.
Like I was not able to view data added to the database.

I tried with mysql 4.1.21 and added 3.1.14 as mysql connector.Then it worked fine.

Thank you very much !!!!!!



Posted by Nisha on Monday, 02.12.07 @ 09:55am | #7493

gud example. keep the gud work.

Posted by raju on Thursday, 02.8.07 @ 05:17am | #6697

This website contains very useful tutorials...illustrated in a very simple way...most of the tutorials helped me to learn & experiment new things in java world....
thanks....

Posted by sam mg on Wednesday, 02.7.07 @ 16:26pm | #6602

very nice tutorial man.
i hav already worked on hibernate,
just now saw ur code,
for beginners it is very very useful.
pl continue, by creating these kind of,
simple tuts..
thank u..

Posted by Yesudas S on Tuesday, 02.6.07 @ 12:57pm | #6374

plz help me get the ddl statements in an file.im not getting it inspite of providing the attribute <schemaexport output="hello.sql"

Posted by meera thomas on Monday, 02.5.07 @ 13:31pm | #6144

Thankyou... thankyou... I've been pulling my hair out trying to wrap my head around hibernate with MySQL and I've searched the net high and low. This simple tute answered more of my questions than any of the examples on the hibernate website or any other that I could find.. great job.

Posted by matt pegg on Thursday, 02.1.07 @ 05:01am | #5057

how to create the config.xml in eclipse IDE

Posted by Rama on Wednesday, 01.31.07 @ 16:38pm | #4913

RoseIndia tutorials are simple enough for beginners like me.

Thank you so much.

Posted by Jithendralal on Wednesday, 01.31.07 @ 13:18pm | #4878

Hi Deepak,

Thanks a lot for such a useful tutorial. I am new to hibernate and now I think this tutorial will help me become familiar with it soon.

Thanks Again

Posted by Mayank PAndya on Thursday, 01.25.07 @ 23:58pm | #4366

Thanx a lot, excellent material.

Posted by Vijay on Thursday, 01.25.07 @ 11:59am | #4306

Hi Deepak,

I am able to run it successfully. I have set ID column as Auto_Increment primary key, so I commented setting ID value and when executing, it is giving error as:
Could not execute JDBC batch update

How to go about it?

Thank you in advance!

Posted by Hussain on Wednesday, 01.24.07 @ 06:56am | #4217

right now if u FirstExample it will not insert the data into the database.

To insert the data we need to add u more line of code i.e as follows

--> Transaction tx = session.beginTransaction();
--> tx.commit();

FirstExample.java
==================


package roseindia.tutorial.hibernate;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


/**
* @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
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
Transaction tx = session.beginTransaction();
//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");
System.out.println("Done");
session.save(contact);
tx.commit();
System.out.println("Done");


}catch(Exception e){
System.out.println("exception");
System.out.println(e.getMessage());
}finally{
// Actual contact insertion will happen at this step
System.out.println("before flush=========================================");
session.flush();
session.close();

}

}
}

Posted by Nitin Somani on Monday, 01.22.07 @ 18:13pm | #4043

hi...

this is a very good tutorial for the beginners....

i would like say thanks to all of u who has done this..

All the best

Hridayesh kalauni

Posted by Hridayesh on Friday, 01.19.07 @ 12:25pm | #3814

hi
iam new to hibernate. iam using hssqldb.jar as a database.
if anything i missed plz rectify me..

1) i properly configured hibernate.cfg.xml & mapping file.
2) i started hsqldb server
3) when run my application am getting this kind of exception

"org.hibernate.HibernateException: NoTransactionManagerLookup specified".

what for this exception is raising i dont understand..but i guess this is for transaction kind of....

anybody can help me "How to fix this impact". i am waiting for your response...

Narayana

Posted by Narayana B on Tuesday, 01.16.07 @ 14:43pm | #3618

hi Deepak,
i tried your hibernateexample all examples are working fine except First Example, it showing same output on the console of eclipse but not inserting the records. but other examples are working fine with database. plz help

Posted by bhushan on Wednesday, 01.10.07 @ 11:43am | #3102

Hi almost i got executed hibernate application.but iam getting one execption that is javax/transaction/synchronized how to eliminate this error. what should i do please reply as soon as
Thanks & regards

Posted by Ramu on Monday, 01.8.07 @ 21:10pm | #2980

nice tuts....vv helpfull

Posted by sidd on Friday, 01.5.07 @ 14:38pm | #2681

Thank you very much!
This is by far the least complicated tutorial for getting started with hibernate. Can't say the same for the rest of them :(

Keep up the good work ;)

Posted by sordan on Thursday, 01.4.07 @ 20:53pm | #2650

nice to get such avery useful code here only

Posted by mahendra bisen on Thursday, 12.28.06 @ 17:51pm | #2156

Dear Sir,
really it was a very nice excersise for me .I am also new to Hibernate.I followed your instruction.
I got the message
Hibernate: insert into CONTACT (FIRSTNAME, LASTNAME, EMAIL, ID) values (?, ?, ?, ?)
but the values are not inserting into database.
Please guide me ,how can i insert the value in table

Posted by Deepak on Tuesday, 12.26.06 @ 16:20pm | #2040

Hi deepak,
This is the best beginners tutorial I have seen till now..
Compared to others it makes the point straight forward, and is quite simple.....
thanks a lot...

Posted by Seshu on Saturday, 12.23.06 @ 17:49pm | #1502

Hi,

Tutorial is good and very useful for the beginners. Clearly explained with the examples. Thanku for one and all who contributed their efforts for this roseindia.net.

Thanks & Regards,
G.Sailatha

Posted by Sai on Friday, 12.22.06 @ 05:50am | #1429

Hi
Your website is very helpful to me,coz i have got from this, Keep it up
Thanks and Regards
Balraj Kumar

Posted by Balraj Kumar on Thursday, 12.21.06 @ 03:34am | #1377

Tutorial is excelent
i am having following problem
when i am running first example in eclipse tables are created but records are not getting in mysql.
Thanks for such a good tutorial :).

Posted by rahul on Wednesday, 12.20.06 @ 17:26pm | #1355

Excellent artical. Very easy to read and suitable for the beginners. Well done Deepak.

cheers,

Posted by Rahul on Monday, 12.18.06 @ 19:27pm | #1197

hello Depak the example is presented very nicely
thanks for ur efforts....keep it up..

Posted by rakesh thakur on Friday, 12.15.06 @ 12:47pm | #1063

Great work! I am very new in Hibernate even today is my first day and my understanding of it is good just coz of RoseIndia and Mr. Deepak. Keep it up.

Posted by Mukesh Kr. Singh on Thursday, 12.14.06 @ 16:29pm | #1024

Hi Harish,

You wrap the session.save() method within transaction block and then commit the transaction.

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
Transaction tx;
try {
tx = session.beginTransaction();
//do some work
Contact contact = new Contact();
contact.setId(3);
contact.setFirstName("Deepak");
contact.setLastName("Kumar");
contact.setEmail("deepak_38@yahoo.com");
session.save(contact);

tx.commit();
}
catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
finally {
session.close();
}

After modifying the code in this way, you will be able to solve the problem.

Thanks
Deepak

Posted by Deepak Kumar on Saturday, 12.9.06 @ 23:54pm | #714

The example is not showing any errors.
But, it is not inserting the record.
Weblogic 8.1 and Oracle 8i environment.

Posted by harish on Saturday, 12.9.06 @ 22:56pm | #712

Need some more information on Bundling of the package and how we can relate to actual senario

Posted by Manoj on Friday, 12.8.06 @ 13:39pm | #628

hi i'm new to hibernate and i need to use mysql maxdb, but have problems with the hibernate.cfg.xml and drivers thta i need to add to the build path of my project can smb help me

Posted by Desislava on Wednesday, 12.6.06 @ 14:34pm | #493

Hello Sir,
I have seen roseindia.net for first time might be this is the best tutorial i have ever seen on Internet which teaches completely from the scratch.

Posted by muneeb on Wednesday, 12.6.06 @ 14:12pm | #490

I am new to hibernate...
I just gone through it...very nice and easy to understand..

Posted by najma on Monday, 12.4.06 @ 15:05pm | #382

I'm new to Hibernate, and this tutorial helped me a lot. Thank you so much Deepak!!

Keep up the good work :)

Posted by semaj on Friday, 12.1.06 @ 10:44am | #298

you have given but somewhat it confused.

Posted by arjun on Monday, 11.27.06 @ 23:17pm | #158

you have given but somewhat it confused.

Posted by arjun on Monday, 11.27.06 @ 20:56pm | #155

you have given but somewhat it confused.

Posted by arjun on Monday, 11.27.06 @ 20:42pm | #154

Hi i'm trying to implement the above example but i got fatal exception . first of all i couldnt able to create sessionfactory. null pointer exception occured at the creating of sessionfactory. pls do advise me. Thanks

Posted by Visalatchi Jayakumar on Monday, 11.27.06 @ 15:36pm | #142

I love this page!
I'm new to java technology and Your website helps me much! I'll recomment this page to my friends.

Thank you very much!

Posted by Nguyen Ngoc Kien on Thursday, 11.23.06 @ 16:18pm | #52

Ask programming questions?

 

 

Back to Tutorial

 

  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification

Tell A Friend
Your Friend Name

 

 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright 2007. All rights reserved.