简体   繁体   English

@transactional 注解中执行的语句

[英]Sentences executed in @transactional annotation

Given the following code:给定以下代码:

public class OrderService {
    @PersistanceContext
    private EntityManager entityManager;

    @Transactional
    public void updateOrder(long orderId, OrderDTO updatedOrder) {
        Order order = entityManager.find(Order.class, orderId);
        if (order != null) {
            order.setName(updated.getName());
        } else {
            throw new EntityNotFoundException(Order.class, orderId);
        }
    }
}

I was asked to point out all the queries that are executed when the updateOrder method is called including transactional sentences.我被要求指出调用updateOrder方法时执行的所有查询,包括事务语句。

My answer was 1 query, the one that retrieves the order by calling entityManager.find(Order.class, orderId) however it seems that is not correct.我的答案是 1 个查询,即通过调用entityManager.find(Order.class, orderId)检索订单的查询,但它似乎不正确。 How is that even possible?这怎么可能呢? I do see the setName method is called on the order but there is not a call to save that order back to the database.我确实看到在订单上调用了setName方法,但没有调用将该订单保存回数据库。

Is there any documentation that explains how this works or any way to see all the sentences executed in that transaction?是否有任何文档可以解释其工作原理或以任何方式查看该交易中执行的所有句子?

When you call find() method,your object becames in persistent state.当你调用 find() 方法时,你的 object 变成了持久的 state。 Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes. Hibernate 将检测对持久 state 中的 object 所做的任何更改,并在完成时将 Z9ED39E2EA9312 单元与数据库同步。 You can read about object states: https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html You can read about object states: https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html

The answer is it depends, the first one for sure is entityManager.find(...) which does a select.答案视情况而定,第一个肯定是entityManager.find(...) ,它执行 select。 And if it finds a record, you are setting a new name( setName(...) ) for which hibernated detects the object as dirty.如果它找到一条记录,您正在设置一个新名称( setName(...) ),hibernated 将 object 检测为脏。 So that it will flush the new data to db.这样它会将新数据刷新到 db。 Hence, as a second call save(...) will be triggered.因此,作为第二次调用save(...)将被触发。 Check here 在这里检查

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

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