[英]Edited/updated values in p:dataTable rowEdit are not available in listener method as they are being overwritten by existing data from database
I'm editing data with <p:dataTable>
row editor as below. 我正在使用
<p:dataTable>
行编辑器编辑数据,如下所示。
<p:dataTable value="#{bean.users}" var="user" editable="true">
<p:ajax event="rowEdit" listener="#{bean.onRowEdit}" />
<p:ajax event="rowEditCancel" listener="#{bean.onRowEditCancel}" />
<p:column>
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{user.firstName}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{user.firstName}" />
</f:facet>
</p:cellEditor>
</p:column>
</p:dataTable>
The backing bean is implemented as below. 支持bean的实现如下。
private List<User> users;
@EJB
private UserService userService;
public List<User> getUsers() {
users = userService.list();
return users;
}
When I enter the new data in the cellEditor and submit it, they are not available in listener method. 当我在cellEditor中输入新数据并提交它时,它们在侦听器方法中不可用。 I noticed that they get overwritten by the data called from the database.
我注意到它们被数据库调用的数据覆盖了。
Why does this happen and how can I avoid it? 为什么会发生这种情况,我该如何避免呢?
Your problem is caused by performing business logic in a getter method. 您的问题是由getter方法中的业务逻辑引起的。 Every iteration over the data table will invoke the getter method.
数据表上的每次迭代都将调用getter方法。 So, while JSF is busy iterating over the data table in order to set the submitted values in the model, the getter calls returns a new list from DB again and again.
因此,当JSF忙于迭代数据表以便在模型中设置提交的值时,getter调用会一次又一次地从DB返回一个新列表。
You're not supposed to perform business logic in a getter method. 您不应该在getter方法中执行业务逻辑。 As long as you're a starter, you'd better refrain from touching the getter (and setter) methods and perform the job elsewhere in an one time called method.
只要你是初学者,你最好不要触及getter(和setter)方法,并在一次性调用方法中执行其他工作。
You likely need a @PostConstruct
(and a true service/DAO class) here: 您可能需要
@PostConstruct
(以及真正的服务/ DAO类):
private List<User> users;
@EJB
private UserService userService;
@PostConstruct
public void init() {
users = userService.list(); // Call the DB here.
}
public List<User> getUsers() {
return users; // Just return the already-prepared model. Do NOT do anything else here!
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.