2017-10-15 111 views
0

讓我們假設一個帶有xhtml頁面,ManagedBean,服務和JPA entityClass的簡單Jsf示例。我有以下結構的很多usecases的:在託管bean中保存更改後如何保持實體最新

  • 保持一個實體在我的豆
  • 請在實體
  • 做渲染更新的實體

一些簡單的例子行動,所以每個人都會明白

實體:

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> 

我想達到的目標:

  • 始終在每個請求中顯示最新的實體!在我的getter

什麼我已經嘗試過

  • 我試着用道取。但是你可以隨處看到這是不好的做法,因爲jsf會多次調用getter(但現在是唯一能讓他們真正保持最新狀態的方法)。
  • 我試過RequestScoped Beans。但是,Bean將在動作完成之前創建,並且不會在更新調用中重新創建,並且值將過期(有意義,因爲這是一個請求,並且請求從點擊按鈕開始)。
  • 我嘗試了ViewScoped Beans,並向我的方法添加了一個空的String返回值。我的希望是,這個重定向將在處理完動作後重新創建Bean。但事實並非如此。
  • 我嘗試在每次使用的方法後手動調用重新獲取函數。但是我在同一個實體上有一些交叉bean操作(我的真實實體比這個例子更復雜)。所以不同的Beans並不總是知道,如果當實體發生變化時。

我的問題:

  • 這可以與任何類型的適用範圍做什麼?假設每個請求都會再次從我的PostConstruct中獲取數據。在getter方法

這似乎是我的一個基本問題

  • 必須有比一個更好的解決方案道取,因爲得到最新的數據是我的應用程序是必要的(數據被改變經常)。

    使用Primefaces 6.1和Wildfly 10.x

  • +0

    你使用什麼ORM工具? – Kaizen

    +0

    JPA實體和休眠保存到MySQL數據庫 – kaiser

    回答

    1

    您對此有何看法? 請求作用域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 
    } 
    
    +0

    我使用而不是f:viewAction,因爲我的主要內容在ui:composition中,所以我不需要f:metadata標籤。 但這似乎很不錯。我的頁面負載很低,數據也是最新的。 非常感謝^^ – kaiser

    相關問題