@Transactional方法中所做的更改不会反映到实体 [英] Changes made in a @Transactional method are not reflected to the Entity

查看:134
本文介绍了@Transactional方法中所做的更改不会反映到实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在服务层中有以下方法,

I have the following method in my Service Layer, which

  1. 通过ID检索实体
  2. 执行对实体的更新
  3. 检索并返回相同的实体

  1. Retrieves an entity by ID
  2. Executes an update to the entity
  3. Retrieves and returns the same entity

@Transactional
@Override
public Order acceptOrder(long orderId){
    Order Order = getOrderById(orderId);                                  // 1
    orderDao.updateOrderStatus(OrderStatus.PENDING_COMPLETION, orderId);  // 2
    return getOrderById(orderId);                                         // 3
}   

服务的方法getOrderById

@Override
public Order getOrderById(long id) {
    return orderDao.get(Order.class, id);
}

DAO的方法updateOrderStatus

    @Override
    public int updateOrderStatus(AppEnums.OrderStatus status, long orderId) {
        String query = "update Order set orderStatus=:status where id=:orderId";
        Query q = getHibernateSession().createQuery(query);
        q.setParameter("status", status);
        q.setParameter("orderId", orderId);
        return q.executeUpdate();
    }

该方法执行时,数据库已成功更新,但返回的实体的状态反映了更新后的状态值.默认情况下,在同一事务中进行的更改是否不可见?

When the method executes the DB is updated successfully but the returned entity's status does not reflect the updated status value. Shouldn't changes made in the same transaction be visible by default?

推荐答案

您可以

(如Deinum先生在评论中所建议)

(As M.Deinum suggested in the comments)

order.setOrderStatus(OrderStatus.PENDING_COMPLETION);  //2
return salesOrderDao.saveOrUpdate(order);              //3

一旦交易更新就提交

@Transactional
@Override
public Order acceptOrder(long orderId){
    Order order = getOrderById(orderId);                                  // 1
    orderDao.updateOrderStatus(OrderStatus.PENDING_COMPLETION, orderId);  // 2
    //commit the transaction                                              // 3
    return getOrderById(orderId);                                         // 4
}  

注意:您将需要以某种方式访问​​该交易.

Note: You will need to access the transaction someway.

您可以使用 Session.evict

orderDao.updateOrderStatus(OrderStatus.PENDING_COMPLETION, orderId);  //2
hibernateSession.evict(order);                                        //3
return getOrderById(orderId);                                         //4

注意:您将需要访问HibernateSession

Note: You will need to access the HibernateSession

但是您可以执行 answer

@Transactional
public void method1(){
    this.updateM1Service();
    this.getDataService();
}

@Transactional (propagation = Propagation.REQUIRES_NEW)
public void updateM1Service(){
    dao.updateM1();
}

@Transactional
public void getDataService(){
    dao.getData();
}

这篇关于@Transactional方法中所做的更改不会反映到实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆