我有一个实体用户的可编辑数据表。该表有一个名为 username 的字段,该字段具有唯一约束
<h:form id="form">
<p:dataTable id="userTable" value="#{users}" var="entity" editable="true" editMode="cell" tableStyle="width:auto">
<p:ajax event="cellEdit" listener="#{userController.onCellEdit}" update="form:msgs form:display form:userTable" />
<p:column headerText="UserID">
<p:outputLabel value="#{entity.id}" />
</p:column>
<p:column headerText="Username">
<p:cellEditor>
<f:facet name="output"><p:outputLabel for="username" value="#{entity.username}" /></f:facet>
<f:facet name="input">
<p:inputText id="username" value="#{entity.username}" >
<f:validateRequired />
<f:validateLength maximum="50" />
</p:inputText>
</f:facet>
</p:cellEditor>
</p:column>
</p:dataTable>
</h:form>
在后备bean userController中,我有以下方法onCellEdit
public void onCellEdit(CellEditEvent event) {
Object newValue = event.getNewValue();
String columnName = event.getColumn().getHeaderText();
facesContext = FacesContext.getCurrentInstance();
User entity = facesContext.getApplication().evaluateExpressionGet(facesContext, "#{entity}", User.class);
if(columnName.equals("Username") {
entity.setUsername((String) newValue);
}
try {
service.createOrUpdateEntity(entity);
}
catch (EJBTransactionRolledbackException ex) {
Throwable t = ex.getCause();
while (t != null) {
t = t.getCause();
if(t.getClass().getSimpleName().equals("SQLIntegrityConstraintViolationException")) {
entity.setUsername((String) event.getOldValue());
facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Duplicate entry for the field username. Write a different username", ""));
break;
}
}
return;
}
catch (Exception e) {
e.printStackTrace();
}
问题在于,当捕获到异常时,构面输入的最终值与构面输出的值不同。在这种情况下,构面输出显示正确的值,而构面输入显示产生异常的值。