我在jsf中练习CRUD,我在“更新”概念上遇到了问题,这是我更新现有数据的基本流程;
假设:应更改学生的名字。
搜索页面
<h:column>
<f:facet name="header">Action</f:facet>
<h:link value="View" outcome="/view/view-student.xhtml">
<f:param value="#{studentSearch.studentID}" name="studentID" />
</h:link>
</h:column>
查看学生页面
<f:metadata>
<f:viewParam name="studentID" value="#{student}"
converter="#{userConverter}"></f:viewParam>
</f:metadata>
<body>
<h:form id="View_and_Edit_Form">
<h:outputLabel for="firstNameOutputText" value="First Name: "
rendered="#{not student.editable}" />
<h:outputText id="firstNameOutputText" value="#{student.firstName}"
rendered="#{not student.editable}" />
<h:outputLabel for="firstNameInputText" value="First Name: "
rendered="#{student.editable}" />
<h:inputText id="firstNameInputText" value="#{student.firstName}"
rendered="#{student.editable}" />
<br />
<h:outputLabel for="lastNameOutputText" value="Last Name: "
rendered="#{not student.editable}" />
<h:outputText id="lastNameOutputText" value="#{student.lastName}"
rendered="#{not student.editable}" />
<h:outputLabel for="lastNameInputText" value="Last Name: "
rendered="#{student.editable}" />
<h:inputText id="lastNameInputText" value="#{student.lastName}"
rendered="#{student.editable}" />
<br />
<h:commandButton value="Edit" action="#{student.setStudentEditable()}"
rendered="#{not student.editable}">
<f:param name="studentID" value="#{student.studentID}"> </f:param>
</h:commandButton>
<h:commandButton type="submit" value="Save"
action="#{studentDAO.updateStudent()}"
rendered="#{student.editable}">
<f:setPropertyActionListener value="#{student}"
target="#{studentDAO.student}" />
<f:param name="studentID" value="#{student.studentID}"></f:param>
</h:commandButton>
</h:form>
</body>
学生DAO
@ManagedBean(name = "studentDAO")
@ViewScoped
public class StudentDao implements Serializable{
Student student;
List<Student> studentList;
private Long studentIDSearch;
private String firstNameSearch;
private String lastNameSearch;
public String updateStudent() {
Session session = HibernateUtil.getSessionfactory().openSession();
System.out.println(this.student.getFirstName());
try {
session.beginTransaction();
session.update(student);
session.getTransaction().commit();
} catch (Exception ex) {
session.getTransaction().rollback();
ex.printStackTrace();
System.out.println("Update Error");
} finally {
session.close();
}
return null;
}
运行应用程序将导致显示学生的旧名(来自学生DAO课程中的updateStudent()方法)。
其他信息:
学生班级本身使用@ViewScoped