简体   繁体   中英

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
 *
 * 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();
                //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("Before Save");
                session.save(contact);
                System.out.println("After Save");
                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();

            }

    }
}

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
Done
Hibernate: insert into CONTACT (FIRSTNAME, LASTNAME, EMAIL, ID) values (?, ?, ?, ?)

You need to wrap your code in a transaction:

session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
// your code
transaction.commit();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM