Sunday, August 7, 2011

insert doesn't works on hibernate??


Source : http://www.coderanch.com/t/219259/ORM/java/insert-doesn-work-hibernate

insert doesn't work on hibernate


Hi,

Whenever I try to insert data through hibernate into DB, it displays all the steps executed but it doesn't insert a new row into the database. Please tell me what could be the possible cause for this.

The code for my class is

package roseindia.tutorial.hibernate;

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

public class FirstExample {

    public static void main(String[] args) {
        Session session = null;

        try {
            // 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();
            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();

        }

    }
}

Nothing happens in a database without a transaction. Have a read of the linked Wiki entry and you should see how to fix this issue.


Below is the working code:

//Transaction object
Transaction transaction = null;

try{
    // This step will read hibernate.cfg.xml and prepare hibernate for use
    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    session =sessionFactory.openSession();
    Transaction transaction = 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");
    session.save(contact);
    /*This bit ur missing*/
    transaction.commit();
    System.out.println("Done");
}


No comments:

Post a Comment