简体   繁体   English

从数据库中获取对象时,JPA(休眠)如何处理事务

[英]How JPA (Hibernate) deal with transaction when fetching Object from database

I'm currently developping an application in java using Hibernate as a persistence manager and JPA as an abstraction of the persistence manage hibernate. 我目前正在使用Hibernate作为持久性管理器,使用JPA作为持久性管理休眠的抽象在Java中开发应用程序。

I'd like to know the impact of wrapping a result query around a transaction. 我想知道将结果查询包装在事务周围的影响。 I know the entity manager must stay open for lazily fetched field bug what about transaction in all this ? 我知道实体管理器必须为延迟获取的现场错误保持开放状态,这在所有这些事务中如何处理?

Here is a code example with transaction activation/desactivation ability. 这是具有事务激活/停用功能的代码示例。

public List<Exportdata> get(Integer max, EntityManager em, Boolean withTransaction) {
    EntityTransaction tx = null;
    try {
        if (withTransaction) {
            tx = em.getTransaction();
            tx.begin();
        }

        Query query = em.createQuery("from Exportdata");
        query.setMaxResults(10);
        List<Exportdata> list = query.getResultList();

        if (withTransaction)
            tx.commit();

        return list;
    } catch (RuntimeException re) {
        if (withTransaction)
            if (tx != null && tx.isActive())
                tx.rollback();

        throw re;
    }
}

What is the difference between enabling or disabling withTransaction when this function is called ? 调用此函数时,启用或禁用withTransaction有什么区别?

Thanks all, Fred 谢谢大家,弗雷德

There is no practical difference here, since you aren't changing any data. 这里没有实际的区别,因为您没有更改任何数据。 The query you execute will generate an SQL select. 您执行的查询将生成一个SQL选择。 Transactions are there to allow you to apply ACID properties to a collection of inserts, updates, etc. 事务在那里允许您将ACID属性应用于插入,更新等的集合。

However , if you begin manipulating the objects in the list returned from this method, calling setters, etc. those changes will be propagated back to the database out-with a transaction on an ad-hoc basis. 但是 ,如果您开始处理此方法返回的列表中的对象,调用设置器等,则这些更改将随临时事务一起传播回数据库。 In other words you'll effectively be working with the db in auto-commit mode. 换句话说,您将在自动提交模式下有效地使用数据库。 This is unlikely to be what you want. 这不太可能是您想要的。

The important thing to understand is that the duration of a persistence context and a transaction can be managed separately. 要了解的重要一点是,可以分别管理持久性上下文和事务的持续时间。 Often though you would want to manage them together. 通常,尽管您希望一起管理它们。

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

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