2

我从一开始就学习休眠。我从 RoseIndia 下载了休眠演示。为特定数据库设置 hibernate.cfg.xml 的配置。并运行以下代码。此处指定的表“联系人”是自动创建的,但下面的代码无法保存新记录。下面的代码有什么问题吗?

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

1 回答 1

7

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

session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
// your code
transaction.commit();
于 2012-06-23T08:51:09.447 回答