休眠:在没有事务对象的情况下保存对象
我有以下代码将对象保存在数据库中,
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.hibernate.Session;
import org.hibernate.Transaction;
import model.Hibernatetest;
public class Test
{
static EntityManagerFactory objEntityManagerFactory;
static Session objSession;
static Transaction objTransaction;
public static void main(String[] args)
{
objSession = (Session)
objEntityManagerFactory.createEntityManager().getDelegate();
//objTransaction = objSession.getTransaction();
//objTransaction.begin();
Hibernatetest obj = new Hibernatetest();
obj.setName("Nobal");
obj.setAddress("wlfjegtjwdfhdg");
objSession.save(obj);
obj.setName("235611111");
objSession.flush();
//objTransaction.commit();
objSession.close();
}
public static void getConnection()
{
Map<String,String> properties = new HashMap<String,String>();
properties.put("hibernate.connection.username", "root");
properties.put("hibernate.connection.password", "root");
properties.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
properties.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernatetest");
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
objEntityManagerFactory = Persistence.createEntityManagerFactory("Hibereg", properties);
}
}
持久性文件如下所示:
<persistence xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="Hibereg">
<class>entities.Hibernatetest</class>
</persistence-unit>
</persistence>
案例1:
问题是,当我使用hibernate-core-5.2.8.jar运行上面的代码,并且不创建任何事务对象(你可以看到我注释了与事务相关的代码),然后上面的代码给了我以下异常。
'TransactionRequiredException' no transaction is in progress.'
但是,如果我取消注释事务的代码,一切正常。
案例2:
但是当我使用hibernate-core-4.1.4.jar运行代码时,通过在上面提供的代码片段中注释事务的代码,它没有给出这样的例外。也就是说,它从不抱怨缺少事务对象,而是将对象保存在数据库中。这是怎么回事?
我通过互联网阅读了执行插入和更新所必需的事务对象(我不确定选择),但是第二个方案是如何成功执行的?