How to handle with Spring BindingResult exception from inner @Entity class validated with Hibernate before persistence

StackOverflow https://stackoverflow.com/questions/18330769

Domanda

I have two @Entity beans. Bean one is "one to many" for second one. Bean1 and Bean2 have JSR303 different annotations validators.

@Entity
class Bean1 {
    @OneToMany
    private List<Bean2> var;

    //other fields marked with JSR303
}

@Entity
class Bean2 {
    //other fields marked with JSR303
}

My task, is to validate inner Bean2. First of all I have Controller with @Validated of Bean1

@Controller
class Controller {
    public String methodPOST(@Validated Bean1 bean1, BindingResult errors)
}

Hibernate automatically validates JSR303 before trying to persist into DB. So, I even don't have any validation exceptions from Bean2, because Spring doesn't handle them, and Hibernate throw it.

I can create something like DTO beans, and validate them, and inner Bean2DTO will be validated if mark it @Valid, and no exception will be thrown from Hibernate side, because there is no validation before persistence. Also in that case I will have populated BindingResult in Controller method.

Is there some solution to get javax.validation.ConstraintViolationException thrown from Hibernate org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(..) into mine BindingResult without two above options.

Also, I can't disable Hibernate auto validation before persistence, due corruption other amount of logic.

Thank you.

È stato utile?

Soluzione

Possible duplicate can be found here

To recap, you need to annotate your nested property with @Valid

@Entity
class Bean1 {
  @OneToMany
  @Valid
  private List<Bean2> var;

  //other fields marked with JSR303
}

@Entity
class Bean2 {
  //other fields marked with JSR303
}

That should also trigger nested validation in Spring (assuming that that also has a JSR-303 validator configured).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top