我正在编写一个@Transactional
方法
@Transactional
方法(也涉及当前更新的实体)(Service2.calculate)我的问题是,在第2点,我做了一个也涉及当前更新实体的选择。外部事务尚未提交,select选择加载旧实体值。所以微积分是基于旧的价值观。
class Service1{
@Autowired
private Service2 service2;
@Transactional(readOnly=false)
public update(final Entry entry) {
repository.save(entry);
// already tried to flush session injecting entityManager
//or to call saveAndFlush, but it doesn't works!
service2.calculate(entry.getContainer());
}
}
class Service2{
@Transactional(readOnly=false)
public calculate(final Container entry) {
//do the job: calculate the sum of the power of each entity grouper by category
List<Report> report = calcRepository.calculate(entry);
//here the report is filled with sum composed also by the of old value of current entity
}
}
class CalcRepository extends PagingAndSortingRepository{
@Query("select new Report(" +
"a.type, " +
"a.combust, "+
"a.container.id, "+
"sum(a.power)) "+
"from Entry a " +
"where ..... " +
"group by a.type, a.combust")
List<Report> calculate(@Param("container") Container container);
}
我正在进行选择以获取当前容器的分组值:每次修改实体时,我都必须重新计算其容器的值。
我该如何解决这个问题?谢谢
答案 0 :(得分:2)
这里发生的是:
由于报告不是托管实体,因此Hibernate使用本机查询来获取它。这意味着它将根据数据库中的实际数据进行评估,而不是修改后的实体数据。由于您尚未提交您的交易,修改后的数据尚未在数据库中。
据我所见,您有多种选择:
Report
成为管理实体。 (并非总是可能)答案 1 :(得分:2)
将Propagation
和Flush
添加到您的服务中:
class Service1 {
@Autowired
private Service2 service2;
@Transactional(propagation=Propagation.REQUIRED)
public update(final Entry entry) {
repository.saveAndFlsuh(entry);
// already tried to flush session injecting entityManager
//or to call saveAndFlush, but it doesn't works!
service2.calculate(entry.getContainer());
}
}
class Service2{
@Transactional(propagation = Propagation.SUPPORTS)
public calculate(final Container entry) {
//do the job: calculate the sum of the power of each entity grouper by category
List<Report> report = calcRepository.calculate(entry);
//here the report is filled with sum composed also by the of old value of current entity
}
}