简体   繁体   English

休眠不保存数据

[英]Hibernate not saving data

I am learning Hibernate from beginning. 我从一开始就学习Hibernate。 I downloaded hibernated demo from RoseIndia. 我从RoseIndia下载了休眠的演示。 Setup configuration of hibernate.cfg.xml for specific database. 针对特定数据库的hibernate.cfg.xml的设置配置。 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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