简体   繁体   English

gethibernatetemplate()。save(object)不持久化数据

[英]gethibernatetemplate().save(object) does not persist data

I have bellow code stuffs and I'm using spring and hibernate 我有下面的代码,并且正在使用spring和hibernate

//main method in main class //主类中的main方法

public static void main(String[] args) {        
        String[] path = new String[]{"applicationContext.xml"};
        ApplicationContext context = new ClassPathXmlApplicationContext(path); 
        serviceObj = (ServiceClassType)context.getBean("serviceBean");
        serviceObj.doTask();  

    }

//service method in service class //服务类中的服务方法

doTask(){
Obj obj=new Obj();
obj.setValue1("value1");
obj.setValue2("value2");
myDao.saveObject(obj);

}

//in dao class //scenario #1 //在dao类中//场景#1

saveObject(Obj obj){
gethibernatetemplate().save(obj);
}

//scenario #2 //方案#2

saveObject(Obj obj){
session = getHibernateTemplate().getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        session.save(obj);
        tx.commit();
}

***scenario #1 does not persists data but scenario #2 working fine. ***方案1不能持久保存数据,但方案2可以正常工作。 Can someone explain why? 有人可以解释为什么吗?

Hibernate Session doesn't work without Transaction in standart configuration. 如果没有标准配置中的“事务处理”,则Hibernate Session将无法工作。 If you add this property <property name="connection.autocommit">true</property> scenario #1 will work . 如果添加此属性,则<property name="connection.autocommit">true</property>方案#1将起作用。

Because Hibernate doesn't commit the transaction by default. 因为默认情况下,Hibernate不提交事务。 I would recommend to use Spring's Transaction Manager to handle this logic, instead of manual commit/rollback. 我建议使用Spring的Transaction Manager来处理此逻辑,而不是手动提交/回滚。 It automatically commits transaction if everything went fine, and rollbacks the transaction in case of any error. 如果一切正常,它将自动提交事务,并在出现任何错误的情况下回滚事务。 With correct Spring configuration your code will look like: 使用正确的Spring配置,您的代码将如下所示:

class ServiceClassType {
   @Transactional 
   public doTask(){
      // update entities with your DAO classes
   }
}

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

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