Hibernate不保存数据

时间:2012-06-23 08:35:20

标签: java hibernate

我从一开始就在学习Hibernate。我从RoseIndia下载了hibernated演示。 为特定数据库设置hibernate.cfg.xml的配置。并运行下面的代码。指定在上面的表'contact'是自动创建的,但是在代码下面无法保存新记录。下面的代码有什么问题吗?

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

            }

    }
}

我的输出如下

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 (?, ?, ?, ?)

1 个答案:

答案 0 :(得分:7)

您需要将代码包装在事务中:

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