通过JPA关系进行Bean验证

Pab*_*blo 2 bean-validation java-ee-6 jsf-2 jpa-2.0

我想使用Bean验证来注释实体中的约束,现在的问题是,实体上的关系也将得到验证吗?例如,假设我有以下实体:

@Entity
@Table(name = "css_empresa")
public class Empresa extends EntidadContactable implements Serializable,
    Convert {
private static final long serialVersionUID = 1L;

@Id
@SequenceGenerator(name = "EMPRESA_ID_GENERATOR", sequenceName = ConstantesSecuencias.SEQ_EMPRESA)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "EMPRESA_ID_GENERATOR")
@Column(name = "cod_empresa", unique = true, nullable = false)
private Long id;

@Column(name = "num_ruc", precision = 13)
private BigDecimal numRuc;

@Column(name = "num_rup", precision = 15)
private BigDecimal numRup;

@Column(name = "txt_direccion_web", length = 255)
private String txtDireccionWeb;

@NotNull
@Column(name = "txt_nombre", nullable = false, length = 255)
private String txtNombre;

@Column(name = "txt_observaciones", length = 255)
private String txtObservaciones;

@OneToOne
@JoinColumn(name = "cod_usuario")
private Usuario administrador;

// bi-directional many-to-one association to DireccionEmpresa
@OneToMany(mappedBy = "empresa", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<DireccionEmpresa> direccionEmpresas;
    --Rest of code ommited for brevity
Run Code Online (Sandbox Code Playgroud)

DireccionEmpresa实体声明如下:

@Entity
@Table(name = "css_direccion_empresa")
public class DireccionEmpresa implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@SequenceGenerator(name = "DIREMPRESA_ID_GENERATOR", sequenceName = ConstantesSecuencias.SEQ_DIREMPRESA)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "DIREMPRESA_ID_GENERATOR")
@Column(name = "cod_direccion_empresa", unique = true, nullable = false)
private Long codDireccionEmpresa;

@Column(name = "sts_predeterminado", nullable = false, length = 1)
private String stsPredeterminado;

@NotNull
@Column(name = "txt_calle_principal", nullable = false, length = 120)
private String txtCallePrincipal;

@NotNull
@Column(name = "txt_calle_secundaria", length = 120)
private String txtCalleSecundaria;

@Column(name = "txt_descripcion", length = 120)
private String txtDescripcion;

@Column(name = "txt_informacion_adicional", length = 120)
private String txtInformacionAdicional;

@NotNull
@Column(name = "txt_numero", nullable = false, length = 10)
private String txtNumero;

@NotNull
@Column(name = "txt_sector", nullable = false, length = 60)
private String txtSector;
Run Code Online (Sandbox Code Playgroud)

现在,问题是保存Empresa时,BeanValidation将检查DireccionEmpresa约束吗?非常感谢。

Gun*_*nar 5

不,DireccionEmpresa在保留的实例时,不会验证处的约束Empresa

通常,级联验证仅在使用@Valid批注对引用(例如普通对象引用或列表)进行批注时才会发生,而不是List<DireccionEmpresa> direccionEmpresas;

但是,即使@Valid使用JPA 2规范在3.6.1.2节中所述的JPA情况,也不会触发这种级联验证来注释该字段:

实体关联(单值或多值)不得发生验证级联(@Valid)。[...这保证]在给定的冲洗周期中,没有任何实体会被多次验证。

因此,DireccionEmpresa只有在持久保存该类型的实例时,才会自动验证at的约束。