“刷新"后未反映的更改带有 Spring JPA 的实体 [英] Changes not reflected after "refreshing" entity with Spring JPA

查看:66
本文介绍了“刷新"后未反映的更改带有 Spring JPA 的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力刷新"一个看起来像这样的实体 (Foo):

I'm strugglingtrying to "refresh" an entity (Foo) that look like this:

public class Foo {

    //...
    @OneToMany(mappedBy = "fooRef", fetch = FetchType.LAZY)
    private List<Bar> bars;
}


public class Bar {

    //...
    @Column(name = "FOO_ID")
    private Long fooRef;
    @Column(name = "STATE")
    @Enumerated(EnumType.STRING)
    private State state;
}

As Spring JPA 没有实现刷新方法,我只是再次查询实体.这是它不起作用的代码,我不知道为什么:

As Spring JPA doesn't implement the refresh method, I just query the entity again. This is the code that it doesn't work and I dont know why:

for(int i=0; i<MAX_RETRIES; i++) {

    List<Bar> bars = foo.getBars();

    // check bars state

    if(someBarIsBad) {
        try {
            TimeUnit.SECONDS.sleep(delay);
        } catch (InterruptedException ignored) {

        }
    } else {
        break;
    }

    foo = fooRepo.findById(fooId);  // "refresh"
}

目标是继续重试,直到所有柱都达到所需状态.我正在做的测试是在循环的最后一条指令处放置一个断点,因此当它中断时,我转到表格并将所有条的状态更改为所需的状态,然后退出循环.问题是新返回的 foobars 没有反映我所做的更改.

The goal is to continue retry until all bars have the desired state. The test I'm doing is placing a breakpoint at the last instruction of the loop, so when it break, I go the the table and change the state of all of the bars to the desired one to then exit the loop. The thing is that the new returned foo, the bars doesn't reflect the change I made.

我试图消除睡眠,但这不是问题.我认为它必须与映射有关.

I tried to remove the sleep, but that is not the problem. I think it must be something with the mapping.

推荐答案

这很可能是因为一切都在单个事务中运行.这会导致 JPA 不从数据库重新加载实体,而是返回会话中已有的实体.

This is most likely because everything is running in a single transaction. This causes JPA to not reload the entity from the database, but to return the one it already has in the session.

确保您在每次刷新"时都处于新事务中或者从会话中驱逐实体,因此它必须再次重新加载.

Either make sure you are in a new transaction on every "refresh" or evict the entity from the session, so it has to get reloaded again.

这篇关于“刷新"后未反映的更改带有 Spring JPA 的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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