讓我們假設一個帶有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
你使用什麼ORM工具? – Kaizen
JPA實體和休眠保存到MySQL數據庫 – kaiser