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

7

23

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 + "]");
    }



}
Juxtapose answered 10/10, 2012 at 15:28 Comment(4)
do you have a @PrePersist in your entity code? If so please paste it in alsoAday
this is very annoying exception, 'cause I never had any problem with Date before..Juxtapose
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.Headwind
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" />Willdon
J
6

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!

Juxtapose answered 16/10, 2012 at 11:39 Comment(1)
I just encountered the same problem and this post helped me! I solved it removing @NotNull and put nullable = false in @Column.Truda
D
39

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.

Deshabille answered 5/6, 2014 at 21:43 Comment(1)
Where can I find the AbstractFacade.java class? Should I make a new class?Overstudy
H
23

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()));
    }
Haire answered 25/4, 2017 at 8:43 Comment(0)
G
6

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.

Greenhouse answered 11/10, 2012 at 5:48 Comment(7)
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=afSQtkcfmikK2G7CLfcL4RJewIGB10oeJuxtapose
still with the same exceptionJuxtapose
whats your primary key is it id?Greenhouse
if your primary key is id, how come you set it to nullGreenhouse
id cannot be null try to figure out why is it null?Greenhouse
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;Juxtapose
to solve the problem I just had to invert the position of the @NotNull validation with @Size validation, that's all guys. Thanks.Juxtapose
J
6

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!

Juxtapose answered 16/10, 2012 at 11:39 Comment(1)
I just encountered the same problem and this post helped me! I solved it removing @NotNull and put nullable = false in @Column.Truda
G
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));
    }
  }
Gagne answered 8/11, 2014 at 13:24 Comment(2)
Thanks for the code, it works perfectly. I guess there's a typo in the method name: constraintValidationsDetected -> constraintViolationsDetectedSo
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.Festinate
P
2

I have spent a few hours struggling with this error while I was trying to persist an entity.

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

This error message is not helpful, quite confusing...

Anyways in my case the cause of the error was - a difference between annotation in Enity

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

And the DataBase column definition:

jpaDiscriminator VARCHAR(15) NOT NULL,

Pikestaff answered 2/12, 2014 at 16:46 Comment(0)
H
2

I had similar issue. In my case the sizes of referenced PK and the FK differed(See example).

Entity A:

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

fk_b referenced ID field of Entity B

Entity B:

id VARCHAR2(4 CHAR)
...

id was here a PK.

Note the sizes of ID(4) and FK_B(5). After changing ID of B to 5 CHAR the error has gone.

Hardcastle answered 15/12, 2016 at 10:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.