如何在托管 bean 中保存更改后使实体保持最新

How to keep entity up to date after saving changes in managed bean

让我们假设一个简单的 Jsf 示例,其中包含一个 xhtml 页面、一个 ManagedBean、一个服务和一个 JPA entityClass。我有很多具有以下结构的用例:

举个简单的例子,大家就明白了

实体:

public class Entity {
     private long id;
     private boolean value;
     ...
     // Getter and Setter
}

道:

public class EntityService {

    // Entity Manger em and other stuff

    public void enableEntity(long id) {
        Entity e = em.find(id);
        e.value = true;
        em.persist(e);
    }
}

托管 Bean:

@ManagedBean
@RequestScoped/ViewScoped
public class EntityBean() {

    @EJB
    private EntityService entityService;

    private Entity entity;

    @PostConstruct
    public void init() {
        // here i fetch the data, to provide it for the getters and setters
        entity = entityService.fetchEntity();
    }

    public void enableEntity() {
        entityService.enableEntity(entity.getId);
    }

    // Getter and Setter
}

最后是一个简单的 xhtml:

<html>
    // bla bla bla

    <h:panelGroup id="parent">
         <h:panelGroup id="disabled" rendered="#{not EntityBean.entity.value}>
              <p:commandButton value="action" action="#{EntityBean.enableEntity}" update="parent" />
         </h:panelGroup>

         <h:panelGroup id="enabled" rendered="#{EntityBean.entity.value}>
               // other stuff that should become visible
         </h:panelGroup>             
    </h:panelGroup>
</html>

我想达到的目标:

我已经尝试过的

我的问题:

这对我来说似乎是一个基本问题,因为获取最新数据对我的应用程序至关重要(数据经常更改)。

使用 Primefaces 6.1 和 Wildfly 10.x

你怎么看这件事? 一个请求范围的 bean,它也将为更新创建,并且每个请求只执行一个 fetchEntity()。

<f:metadata>
  <f:viewAction action="#{entityBean.load()}" onPostback="true"/>
</f:metadata>

@ManagedBean
@RequestScoped
public class EntityBean() {

  @EJB
  private EntityService entityService;

  private Entity entity = null;

  public void load() {}
  public Entity getEntity() {
    if(entity == null) {
      entity = entityService.fetchEntity();
    }
    return entity;
  }
  public void enableEntity() {
    entityService.enableEntity(getEntity().getId);
  }

  // Getter and Setter
}