我一直在制作一个简单的程序,使用 hibernate 框架将员工详细信息保存在 mysql 中,如下所示...
public class Manifest {
Session session;
public static void main(String[] args) {
Employee employee = new Employee("varun");
new Manifest().addEmployee(employee);
}
/* Method to CREATE an employee in the database */
public void addEmployee(Employee employee){
Integer employeeID=null;
SessionGenerator sessionGenerator = new SessionGenerator();
try{
session = sessionGenerator.getSessionToDb();
employeeID = (Integer) session.save(employee);
System.out.println(employeeId);
}catch (HibernateException e) {
e.printStackTrace();
}finally {
session.close();
}
}
}
我知道我应该使用 session.beginTransaction();
& tx.commit()
但我的问题是为什么这里没有抛出异常在我的例子中,它在控制台上打印 employeeId 但没有在数据库中进行任何输入。这背后的原因是什么???
最佳答案
1) Session.save() 可能会在事务边界之外执行 INSERT:save() 方法返回一个标识符,如果必须执行 INSERT 以获取标识符(例如“identity”生成器),这个 INSERT 立即发生(为了获得身份),无论您是在事务内部还是外部。
2) 如果你设置:即使没有交易也可能发生提交:
<property name="connection.autocommit">true</property>
这就是为什么不引发异常的原因
查看这篇文章(使用 Hibernate 进行非事务性工作):https://developer.jboss.org/wiki/Non-transactionalDataAccessAndTheAuto-commitMode
关于java - 在不创建事务实例的情况下使用 hibernate 在数据库中进行插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26449538/