Java 休眠不保存数据
我从一开始就在学习冬眠。我从RoseIndia下载了休眠演示。 为特定数据库设置hibernate.cfg.xml的配置。并在代码下面运行。在此处“contact”指定的表将自动创建,但下面的代码无法保存新记录。下面的代码有什么错误吗Java 休眠不保存数据,java,hibernate,Java,Hibernate,我从一开始就在学习冬眠。我从RoseIndia下载了休眠演示。 为特定数据库设置hibernate.cfg.xml的配置。并在代码下面运行。在此处“contact”指定的表将自动创建,但下面的代码无法保存新记录。下面的代码有什么错误吗 package roseindia.tutorial.hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.C
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();
那么是否存在异常,或者它是否打印“保存后”?它打印“保存后”。。。也不例外。。。让我把输出…输出附加到问题。。。顺便说一句,谢谢你回复Jon…是因为这个警告吗?不,警告是关于日志记录的,仅此而已。默认情况下,Hibernate将autocommit设置为false。但是,诸如session.close()之类的调用可能会提交未提交的事务,这取决于您使用的JDBC驱动程序。