【发布时间】:2017-12-18 01:30:58
【问题描述】:
在我的课堂上,我需要验证并保存运动状态。我不知道把这个验证放在哪里。我想我最好把它放在模型层而不是我的 bean 中。
我正在这样做:
1 - 运动
@SuppressWarnings("serial")
@Entity
public class Movimentacao implements Serializable, Entidade {
...
@Column(nullable=false)
@NotNull
@DecimalMin("0.01")
private BigDecimal valor;
@Column(nullable=false)
@NotNull
@DecimalMin("0.01")
private BigDecimal valorQuitado;
@Enumerated(EnumType.STRING)
@Column(nullable=false, length=1)
private MovimentacaoStatus status;
...
public void setStatus(MovimentacaoStatus status) {
this.status = status;
}
}
2 - form.xhtml
<!-- show only on edit mode (status not null) -->
<h:outputText id="status" value="#{movimentacaoBean.movimentacao.status.descricao}" rendered="#{movimentacaoBean.movimentacao.status ne null}" />
3 - MovimentacaoBean
public String salvar() throws Exception{
movimentacaoService.salvar(movimentacao);
this.movimentacao = null;
this.todos = null;
context.addMessage(null, new FacesMessage("Movimentação salva com sucesso", ""));
context.getExternalContext().getFlash().setKeepMessages(true);
return "pretty:financeiro-lista";
}
状态不是由用户定义的。我应该把验证放在哪里?设置状态?
如果我将 setStatus 更改为(例如):
public void setStatus() {
//example. The real Business rules are other.
this.status = MovimentacaoStatus.P;
}
或
public void setStatus(MovimentacaoStatus status) { //status variable never used...
//example. The real Business rules are other.
this.status = MovimentacaoStatus.P;
}
我收到以下错误(因为 MovimentacaoBean 没有收到来自 form.xhtml 的状态):
原因:java.sql.SQLIntegrityConstraintViolationException:列 “状态”不能为空
我应该如何以及在哪里放置状态的业务规则?当我编辑记录时,同样的问题也适用。根据“valor”和“valorQuitado”,状态可能会改变。编辑模式的区别在于 status 属性在 form.xhtml 上可见(只读 - outputText)
【问题讨论】:
-
你应该把验证放在你的bean中。在您对 Movimentacao 执行保存之前。您也可以在字段中设置 required (使用枚举 selectOneMenu 是最佳选择)。
-
@Milkmaid 也许在 MovimentacaoService 上更好,对吧?因为如果我需要在 JSF 的其他技术上使用相同的类,我不会有耦合。
标签: jakarta-ee bean-validation