如何在JSF中编辑数据库表

时间:2011-05-11 07:43:44

标签: jsf jdbc datatable jsf-2

我有一个bean类,其id,firstName,lastName属性具有公共getter和setter,以及updateEmployee方法。

我正在使用以下jsf页面来获取数据库表值。

当我点击更新按钮时,会显示成功页面,但数据库中的值不会更改。任何人都可以告诉我为什么vales没有在数据库中进行更改的原因吗?

提前致谢。

JSF页面:

<h:dataTable value="#{tableBean.employeeList}" var="employee" border="1">
   <h:column>
          <f:facet name="header">First name</f:facet>
          <h:inputText value="#{employee.firstName}" />
   </h:column>

   <h:column>
          <f:facet name="header">Last name</f:facet>
          <h:inputText value="#{employee.lastName}" />
   </h:column>
</h:dataTable>
<h:commandButton value = "update" action="#{employee.updateEmployee}"/>

Employee.java:

public String updateEmployee(){
   String query = "update employee set firstName = ?,lastName = ? where id = 1";         
   pstmt = conn.prepareStatement(query);
   pstmt.setString(2,this.firstName);
   pstmt.setString(3,this.lastName); 
   pstmt.executeUpdate(); // execute update statement
   conn.commit();
   committed = true;
   return "success.xhtml";
   }catch (Exception e) {
       e.printStackTrace();
       return null;
   } finally {
      try{
         if (!committed) conn.rollback();
              pstmt.close();
          conn.close();
       }catch(Exception e){
            e.printStackTrace();
      }
    }

2 个答案:

答案 0 :(得分:1)

如果您的辅助bean中有相应的属性,则会自动绑定您的值。

您必须提交数据才能更新bean值。在表单中添加commandButton或commandLink,如下所示:

<h:form>
 <h:dataTable> ... </h:dataTable>
 <h:commandButton value="Submit" action="tableBean.actionMethod">
</h:form>

答案 1 :(得分:1)

查询中只有两个参数占位符,但稍后会引用第二个和第三个参数:

pstmt.setString(2,this.firstName);
pstmt.setString(3,this.lastName);