【问题标题】:How can I use Hibernate Template object for persisting multiple transient objects in one transaction如何使用 Hibernate Template 对象在一个事务中持久化多个瞬态对象
【发布时间】:2014-12-17 14:53:29
【问题描述】:

我需要使用 Hibernate 模板将两个瞬态/POJO 对象存储到数据库中。例如,有两个对象 Employee 和 Address。显然我需要先存储员工然后地址,如果存储员工对象导致任何问题,那么地址对象一定不能存储。我可以使用原始编码来执行此操作,例如获取会话、开始事务、持久化两个对象然后提交事务。 我想使用 Hibernate 模板执行这种类似的行为。

【问题讨论】:

    标签: spring hibernate


    【解决方案1】:

    就像你提到的那样。这是流程

    session.beginTransaction();
    
    employeeHybernateTemplateDao.save(employee);  // this will run under the transaction boundaries declared above
    
    addressHybernateTemplateDao.save(address);    // this will run under the transaction boundaries declared above
    
    session.getTransaction().commit();
    

    employeeHybernateTemplateDao 将是您创建的在 save 方法中实现 hybernatetemplate 功能的 DAO,如下所示

    HibernateTemplate template = new HibernateTemplate(sessionFactory);
    
    public void save(Employee employee){
         template.save(employee);        
    
    }
    

    【讨论】:

    • 谢谢宙斯,好主意,为什么我没有想到这个 ;-)
    猜你喜欢
    • 2013-01-06
    • 2011-06-14
    • 1970-01-01
    • 2013-10-27
    • 1970-01-01
    • 2010-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多