Ketan Ketan - 1 year ago 74
Java Question

Hibernate not saving data

I am learning Hibernate from beginning. I downloaded hibernated demo from RoseIndia.
Setup configuration of hibernate.cfg.xml for specific database. And ran below code. Tables specified overhere 'contact' is created automatically but below code can't save the new record. Is there any thing wrong in below code?

package roseindia.tutorial.hibernate;

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

* @author Deepak Kumar
* Hibernate example to inset data into Contact table
public class FirstExample {
public static void main(String[] args) {
Session session = null;

// This step will read hibernate.cfg.xml and prepare hibernate for use
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
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();
System.out.println("Before Save");;
System.out.println("After Save");
}catch(Exception e){
// Actual contact insertion will happen at this step



My Out put is as below

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

Answer Source

You need to wrap your code in a transaction:

session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
// your code
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download