23

我想存储birthdate,所以我选择date了 MySQL,当我基于我的数据库创建实体时,结果是这样的:

import java.util.Date;

    // ..code
    @NotNull(message="fill you birthdate")
    @Temporal(TemporalType.DATE)
    private Date birthdate;

但是当我尝试坚持时,它给了我这个错误:

对回调事件执行自动 Bean 验证时违反了 Bean 验证约束:'prePersist'。有关详细信息,请参阅嵌入式 ConstraintViolations。

我在这里做错了什么?我正在阅读有关在 Google 中定义时区的内容,我来自巴西,我该怎么做?

编辑

package entity;

import java.io.Serializable;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;

import java.util.Date;
import java.util.List;


/**
 * The persistent class for the user database table.
 * 
 */
@Entity
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;

    @Temporal(TemporalType.DATE)
    private Date birthdate;

    @NotNull(message="informe seu e-mail")
    @Email(message="e-mail inválido")
    private String email;

    @NotNull(message="informe seu gênero")
    private String gender;

    private String image;

    @NotNull(message="informe seu nome completo")
    private String name;

    @Size(min=6,max=16, message="senha com no mínimo: 6 dígitos e no máximo 16 dígitos")
    @NotNull(message="informe sua senha")
    private String password;

    //bi-directional many-to-one association to Document
    @OneToMany(mappedBy="user")
    private List<Document> documents;

    //bi-directional many-to-one association to QuestionQuery
    @OneToMany(mappedBy="user")
    private List<QuestionQuery> questionQueries;

    //bi-directional many-to-one association to Team
    @OneToMany(mappedBy="user")
    private List<Team> teams;

    public User() {
    }

    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Date getBirthdate() {
        return this.birthdate;
    }

    public void setBirthdate(Date birthdate) {
        this.birthdate = birthdate;
    }

    public String getEmail() {
        return this.email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getGender() {
        return this.gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getImage() {
        return this.image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getName() {
        return this.name;
    }

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

    public String getPassword() {
        return this.password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public List<Document> getDocuments() {
        return this.documents;
    }

    public void setDocuments(List<Document> documents) {
        this.documents = documents;
    }

    public List<QuestionQuery> getQuestionQueries() {
        return this.questionQueries;
    }

    public void setQuestionQueries(List<QuestionQuery> questionQueries) {
        this.questionQueries = questionQueries;
    }

    public List<Team> getTeams() {
        return this.teams;
    }

    public void setTeams(List<Team> teams) {
        this.teams = teams;
    }

    public void print() {
        System.out.println("User [id=" + id + ", birthdate=" + birthdate + ", email="
                + email + ", gender=" + gender + ", image=" + image + ", name="
                + name + ", password=" + password + "]");
    }



}
4

7 回答 7

38

我遇到了同样的问题,但经过数小时寻找答案,我终于找到了....您应该编辑AbstractFacade.java类并添加此代码

public void create(T entity) {

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<T>> constraintViolations = validator.validate(entity);
    if(constraintViolations.size() > 0){
        Iterator<ConstraintViolation<T>> iterator = constraintViolations.iterator();
        while(iterator.hasNext()){
            ConstraintViolation<T> cv = iterator.next();
            System.err.println(cv.getRootBeanClass().getName()+"."+cv.getPropertyPath() + " " +cv.getMessage());

            JsfUtil.addErrorMessage(cv.getRootBeanClass().getSimpleName()+"."+cv.getPropertyPath() + " " +cv.getMessage());
        }
    }else{
        getEntityManager().persist(entity);
    }
}

现在,此方法将提醒您哪个属性以及它未通过验证的原因。我希望这对你有用,就像对我一样。

于 2014-06-05T21:43:08.973 回答
23

我有一个捷径,在你持久化实体的地方捕获以下异常。在我的例子中,它在 EJB add 方法中。我在哪里em.persist()。然后检查服务器日志,您将看到哪个属性违反了约束。

catch (ConstraintViolationException e) {
       log.log(Level.SEVERE,"Exception: ");
       e.getConstraintViolations().forEach(err->log.log(Level.SEVERE,err.toString()));
    }
于 2017-04-25T08:43:07.633 回答
6

该错误显示您尝试保留的实体未通过数据库约束,因此请在实际插入之前尝试确定您要插入数据库的确切值。

并通过评论/省略注释来尝试@NotNull

于 2012-10-11T05:48:06.147 回答
5

我为解决我的问题所做的是颠倒顺序@Size@NotNull

前:

@Size(min=6,max=16, message="senha com no mínimo: 6 dígitos e no máximo 16 dígitos")
@NotNull(message="informe sua senha")
private String password;

后:

@NotNull(message="informe sua senha")
@Size(min=6,max=16, message="senha com no mínimo: 6 dígitos e no máximo 16 dígitos")
private String password;

我不知道为什么这个命令这么重要,但它确实 =] 谢谢大家!

于 2012-10-16T11:39:28.237 回答
5

当然,Iomanip 的回答是完全正确的!我只是将其扩展了一点。也许这也有帮助:

  private boolean constraintValidationsDetected(T entity) {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<T>> constraintViolations = validator.validate(entity);
    if (constraintViolations.size() > 0) {
      Iterator<ConstraintViolation<T>> iterator = constraintViolations.iterator();
      while (iterator.hasNext()) {
        ConstraintViolation<T> cv = iterator.next();
        System.err.println(cv.getRootBeanClass().getName() + "." + cv.getPropertyPath() + " " + cv.getMessage());

        JsfUtil.addErrorMessage(cv.getRootBeanClass().getSimpleName() + "." + cv.getPropertyPath() + " " + cv.getMessage());
      }
      return true;
    }
    else {
      return false;
    }
  }

  public void create(T entity) {
    if (!constraintValidationsDetected(entity)) {
      getEntityManager().persist(entity);
    }
  }

  public T edit(T entity) {
    if (!constraintValidationsDetected(entity)) {
      return getEntityManager().merge(entity);
    }
    else {
      return entity;
    }
  }

  public void remove(T entity) {
    if (!constraintValidationsDetected(entity)) {
      getEntityManager().remove(getEntityManager().merge(entity));
    }
  }
于 2014-11-08T13:24:41.813 回答
2

当我试图持久化一个实体时,我花了几个小时来解决这个错误。

Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'preUpdate'. Please refer to embedded ConstraintViolations for details.

此错误消息没有帮助,相当混乱......

无论如何,在我的情况下,错误的原因是 - Enity 中的注释之间的区别

@Size(min = 1, max = 10)
@Column(name = Utilizator.JPA_DISCRIMINATOR)
private String jpaDiscriminator;

和数据库列定义:

jpaDiscriminatorVARCHAR(15) 非空,

于 2014-12-02T16:46:09.803 回答
2

我有类似的问题。在我的情况下,引用的 PK 和 FK 的大小不同(参见示例)。

实体 A:

some_pk   INTEGER NOT NULL,
fk_b      VARCHAR2(5 CHAR)
...

fk_b 引用实体 B 的 ID 字段

实体 B:

id VARCHAR2(4 CHAR)
...

id在这里是一个PK。

注意 ID( 4 ) 和 FK_B( 5 ) 的大小。将 B 的 ID 更改为5 CHAR后,错误消失了。

于 2016-12-15T10:18:24.583 回答