Bean验证成功但在jpa merge方法上失败

时间:2014-10-26 10:09:01

标签: jpa bean-validation

我想用merge方法持久保存实体(MyEntity)。该实体有一些bean验证。

public class MyEntity extends AbstractEntity {


@Basic(optional = false)
@Column(name = "city", length = 255, nullable = false)
@NotNull
@NotEmpty(message = "{myentity.validation.size.name}")
private String city;
private String number;
@Basic(optional = false)
@Column(name = "zipcode", length = 255, nullable = false)
@NotNull    
private String zipcode;
private String phoneNumber;
@Email(message = "{myentity.validation.conform.email}")
@Size(min = 2, max = 100, message = "{myentity.validation.size.email}")
private String email;
private String website;
private String gpsLocation;

@ElementCollection()
@CollectionTable(name = "translation_poi", joinColumns = @JoinColumn(name = "point_id"))
@MapKeyJoinColumn(name = "locale")    
@NotEmpty
private Map<Locale, MyEntityI18n> translations = new HashMap<>();

}

 @Embeddable
public class MyEntityI18n implements java.io.Serializable {
    @Basic(optional = false)
    @Column(name = "name", length = 255, nullable = false)
    @NotNull
    @NotEmpty(message = "{myentity.validation.size.name}")
    private String name;
    @Column(name = "comment", length = 1200)
    private String comment;
    @Column(name = "short_description", length = 1200)
    private String shortDescription;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

合并在现有实体值上成功,但是对于新实体,尽管以下验证成功,但合并失败。

 private boolean validate(MyEntity poi) {

    boolean result = true;
    Set<ConstraintViolation<MyEntity>> constraintViolations = validator.validate(poi);
    if (constraintViolations.size() > 0) {
        result = false;
        for (ConstraintViolation<MyEntity> constraints : constraintViolations) {
            FacesContext context = FacesContext.getCurrentInstance();
            String message = constraints.getPropertyPath() + " " + constraints.getMessage();
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, constraints.getMessage(), message));
        }
    }
    return result;
}

1 个答案:

答案 0 :(得分:0)

尝试将@Valid添加到MyEntity.translations属性。我认为您的验证方法没有考虑MyEntityI18n.name验证。

关于合并失败,您是否在MyEntityI18n.name字段上有一个非空数据库约束?

祝你好运!