p:dataTable rowEdit中的编辑/更新值在侦听器方法中不可用,因为它们被数据库中的现有数据覆盖 [英] Edited/updated values in p:dataTable rowEdit are not available in listener method as they are being overwritten by existing data from database

查看:951
本文介绍了p:dataTable rowEdit中的编辑/更新值在侦听器方法中不可用,因为它们被数据库中的现有数据覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用< p:dataTable> 行编辑器编辑数据。

I'm editing data with <p:dataTable> row editor as below.

<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>

支持bean的实现如下。

The backing bean is implemented as below.

private List<User> users;

@EJB
private UserService userService;

public List<User> getUsers() {
    users = userService.list();
    return users;
}

当我在cellEditor中输入新数据并提交它们时,它们不是在侦听器方法中可用。我注意到他们被数据库中调用的数据所覆盖。

When I enter the new data in the cellEditor and submit it, they are not available in listener method. I noticed that they get overwritten by the data called from the database.

为什么会发生这种情况,我该如何避免?

Why does this happen and how can I avoid it?

推荐答案

您的问题是由getter方法执行业务逻辑引起的。数据表中的每一次迭代将调用getter方法。所以,尽管JSF正在忙于遍历数据表,以便在模型中设置提交的值,但是getter调用会一次又一次地从DB返回一个新的列表。

Your problem is caused by performing business logic in a getter method. Every iteration over the data table will invoke the getter method. 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.

你不应该在getter方法中执行业务逻辑。只要你是一个初学者,你最好不要触摸getter(和setter)方法,并在一段时间内称为方法执行工作。

You're not supposed to perform business logic in a getter method. 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.

您可能需要一个 @PostConstruct (和一个真正的服务/ DAO类):

You likely need a @PostConstruct (and a true service/DAO class) here:

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!
}



另请参见:




  • 为什么JSF多次呼叫getter

  • See also:

    • Why JSF calls getters multiple times
    • 这篇关于p:dataTable rowEdit中的编辑/更新值在侦听器方法中不可用,因为它们被数据库中的现有数据覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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