JPA多对一关系更新父级中的聚合列

时间:2018-11-28 12:06:00

标签: java spring hibernate jpa spring-data-jpa

在Java Spring Rest应用中,我具有以下域对象:

@Entity
@Table(name = "order")
public class Order implements Serializable {
    ....
    @OneToMany(mappedBy = "order", orphanRemoval = true)
    private Set<PurchaseOrderItem> purchaseOrderItems = new HashSet<>();

    @NotNull
    @Column(name = "total_net", precision = 10, scale = 2, nullable = false)
    private BigDecimal totalNet;
}

@Entity
@Table(name = "order_item")
public class OrderItem implements Serializable {
    @ManyToOne(optional = false)
    @NotNull
    @JsonIgnoreProperties("")
    @JsonIgnore
    private Order order;

    @NotNull
    @Column(name = "total_net", precision = 10, scale = 2, nullable = false)
    private BigDecimal totalNet;
}

订单实体中有一个聚合列-该列应包含每个orderItem的所有totalNet的总和,并且在添加或删除orderItem时,也应更新订单的totalNet。

实现此目标的最佳方法是什么?

当前的实现是通过

之类的服务进行的
@Service
@Transactional
public class OrderItemService {

  public OrderItemDTO save(OrderItemDTO orderItemDTO) {
    orderItem orderItem = mapper.toEntity(orderItemDTO);

    orderItem = orderItemRepository.save(orderItem);

    if (orderItemDTO.getOrderId() != null) {
        OrderDTO orderResult = orderService.findOne( orderItemDTO.getOrderId()).get();
        orderService.save(orderResult);
        //total is calculated in save method of parent
    }

    return mapper.toDto(orderItem);
  }
}

这似乎是错误的流程... 在此处使用带有@PostUpdate @PostRemove的EntityEventListeners是否正确?

0 个答案:

没有答案