使用Facelets + JPA持久保存实体时如何比较和验证2个字段?

时间:2010-12-09 03:16:17

标签: jpa seam validation facelets

我正在使用Facelets的Seam 2.2,我需要验证来自JPA实体的2个字段,比较两者以在插入之前检查其值。

这是我的好处的碎片:

@Entity
@Scope(ScopeType.CONVERSATION)
@Name("metaAbastecimento")
public class MetaAbastecimento  implements Serializable{
 private float abastecimentoMinimo;

 private float abastecimentoMaximo;


 @Column
 public float getAbastecimentoMinimo() {
  return abastecimentoMinimo;
 }

 @Column
 public float getAbastecimentoMaximo() {
  return abastecimentoMaximo;
 }

 public void setAbastecimentoMinimo(float abastecimentoMinimo) {
  this.abastecimentoMinimo = abastecimentoMinimo;
 }

 public void setAbastecimentoMaximo(float abastecimentoMaximo) {
  this.abastecimentoMaximo = abastecimentoMaximo;
 }
}

比我有一个持久存在这个实体的xhtml:

<rich:panel>
        <f:facet name="header">Detalhe de Meta de Abastecimento</f:facet>


        <s:decorate id="abastecimentoMinimo" template="../layout/display.xhtml">
            <ui:define name="label">Meta(R$) de Abastecimento M&iacute;nimo</ui:define>
            <h:outputText value="#{metaAbastecimentoHome.instance.abastecimentoMinimo}">
            </h:outputText>
        </s:decorate>

        <s:decorate id="abastecimentoMaximo" template="../layout/display.xhtml">
            <ui:define name="label">Meta(R$) Abastecimento M&aacute;ximo</ui:define>
            <h:outputText value="#{metaAbastecimentoHome.instance.abastecimentoMaximo}"/>
        </s:decorate>

        <div style="clear:both"/>

    </rich:panel>

我需要比较这两个字段,然后再坚持它们并检查它们是否与0f不同,以及abastecimentoMinimo是否小于abastecimentoMaximo。我怎么能用Seam + Facelets + JPA做到这一点?

[]中

1 个答案:

答案 0 :(得分:2)

JSF 1中的交叉字段验证是不可能的。所以你必须手动完成。

在您的情况下,可以使用@PrePersist@PreUpdate来完成此操作,也可以手动在操作方法中执行此操作。

给你一个提示。避免将Entity bean作为seam组件。最好制作一个单独的接缝组件。

原因如下:

实体bean可以绑定到上下文变量并充当接缝组件。由于实体除了上下文标识之外还具有持久标识,因此实体实例通常在Java代码中显式绑定,而不是由Seam隐式实例化。

实体bean组件不支持双射或上下文划分。调用实体bean也不会触发验证。 实体bean通常不用作JSF动作侦听器,但通常用作支持bean,为JSF组件提供显示或表单提交的属性。特别是,通常使用实体作为支持bean,以及无状态会话bean动作侦听器来实现创建/更新/删除类型功能。 默认情况下,实体bean绑定到对话上下文。他们可能永远不会受到无国籍情境的束缚。

请注意,在集群环境中,将实体bean直接绑定到会话或会话范围的Seam上下文变量的效率要低于在有状态会话Bean中保存对实体bean的引用的效率。因此,并非所有Seam应用程序都将实体bean定义为Seam组件。

@Entity
public class MetaAbastecimento {
  .....

    //If check fails you can throw exception, thus rollback will occur, and commit will not be made
    @PrePersist
    @PreUpdate
    public void check() {
      if(abastecimentoMinimo == 0f || abastecimentoMaximo == 0f && abastecimentoMinimo > abastecimentoMaximo) 
        throw new RuntimeException("Failed!");
    }
}