gpt4 book ai didi

java - hibernate 不保存数据

转载 作者:行者123 更新时间:2023-12-03 07:50:13 25 4
gpt4 key购买 nike

我正在从头学习 Hibernate。我从 RoseIndia 下载了 hibernate 演示。为特定数据库设置 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 (?, ?, ?, ?)

最佳答案

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

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

关于java - hibernate 不保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11168048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com