Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'

52,524

Solution 1

What I did to solve my problem was to invert the order @Size and @NotNull

before:

@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;

after:

@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;

I don't know why this order matter this much, but it does =] Thank you everyone!

Solution 2

I got the same problem, but after hours looking for the answer, Finally I Found it.... You should edit your AbstractFacade.java class and add this code

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);
    }
}

Now this method will alert you which property and why it fails the validation. I hope this works for you, as it does for me.

Solution 3

I got a shortcut way,Catch the following exception where you persisting the entity. In my case its in the EJB add method. where I am doing em.persist(). Then check the server log, you will see which attribute having constrain violation.

catch (ConstraintViolationException e) {
       log.log(Level.SEVERE,"Exception: ");
       e.getConstraintViolations().forEach(err->log.log(Level.SEVERE,err.toString()));
    }

Solution 4

The error displays that the entity you are trying to persist is failing database constraints, so try determining the exact values you are inserting into the database before you actually insert.

and try out by commenting/ommitting @NotNull annotation also.

Solution 5

Of course, Iomanip's answer is completely right! I've just extended it a little bit. Maybe this helps too:

  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));
    }
  }
Share:
52,524

Related videos on Youtube

Valter Silva
Author by

Valter Silva

Updated on November 14, 2020

Comments

  • Valter Silva
    Valter Silva over 3 years

    I would like to store birthdate so I chose date at MySQL, when I create my entities based in my database, it turns out like this:

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

    But when I try to persist it gives me this error:

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

    What am I doing wrong here ? I was reading something about define time zone in Google, I'm from Brazil, how should I do that ?

    EDIT

    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 + "]");
        }
    
    
    
    }
    
    • Marthin
      Marthin over 11 years
      do you have a @PrePersist in your entity code? If so please paste it in also
    • Valter Silva
      Valter Silva over 11 years
      this is very annoying exception, 'cause I never had any problem with Date before..
    • Tasos P.
      Tasos P. over 11 years
      This is a quite generic error, it might come for validation errors on some other field of your model. My usual approach is: Enable SQL and parameter logging (easy for EclipseLink but I think most JPA providers support it) or issue a try/catch em.flush() (to force commit instead of waiting for the container to commit) and loop the ConstraintViolations in order to locate the issue.
    • BalusC
      BalusC over 11 years
      To get better answers from JPA users, please mention JPA impl/version, DB server vendor/version and JDBC driver version used. Your first step would be trying to disable bean validation in persistence.xml using <property name="javax.persistence.validation.mode" value="none" />
  • Valter Silva
    Valter Silva over 11 years
    This is how I'm writing my form in database:User [id=null, birthdate=Sun Sep 29 21:00:00 BRT 1985, [email protected], gender=M, image=null, name=valter, password=afSQtkcfmikK2G7CLfcL4RJewIGB10oe
  • Valter Silva
    Valter Silva over 11 years
    still with the same exception
  • Swarne27
    Swarne27 over 11 years
    whats your primary key is it id?
  • Swarne27
    Swarne27 over 11 years
    if your primary key is id, how come you set it to null
  • Swarne27
    Swarne27 over 11 years
    id cannot be null try to figure out why is it null?
  • Valter Silva
    Valter Silva over 11 years
    Sorry for the delay in answer, but now I found the problem, it's my constraint here: @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;
  • Valter Silva
    Valter Silva over 11 years
    to solve the problem I just had to invert the position of the @NotNull validation with @Size validation, that's all guys. Thanks.
  • Micer
    Micer about 9 years
    Thanks for the code, it works perfectly. I guess there's a typo in the method name: constraintValidationsDetected -> constraintViolationsDetected
  • javydreamercsw
    javydreamercsw about 9 years
    Works fine until you have to remove. It causes StackOverflowError in a loop between merge and remove. I had to disable the remove method to make it work.
  • codyLine
    codyLine almost 7 years
    I just encountered the same problem and this post helped me! I solved it removing @NotNull and put nullable = false in @Column.
  • LeDerp
    LeDerp over 6 years
    Where can I find the AbstractFacade.java class? Should I make a new class?