0

I'm using EclipseLink 2.5 with JPA 2.1 in standalone java application.

Some field are marked with @Basic(optional=false), but even with null value I didn't get any error before commit. The constraint is set on database so I got a JDBC exception.

Adding Hibernate Validator to project and setting validation mode to callback didn't help.

Only with @NotNull annotation on field I got exception: javax.validation.ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'. Please refer to embedded ConstraintViolations for details. which is not very specific and does not inform where the problem is.

I would like to know if there is any way to make this message look more robust: like field name not set or something like this and force eclipselink to check optional=false.

EDIT: I know the difference between JPA and Bean Validation. I am trying to perform validation with JPA only, using optional=false. As far as I know (@Basic(optional = false) vs @Column(nullable = false) in JPA) @Basic(optional=false) should be checked at runtime and @Column(nullable=false) should be used to make column nonnullable in the database.

I'm looking for a method to display violations with out catching ConstraintViolations everywhere.

Community
  • 1
  • 1
Krystian Lieber
  • 481
  • 3
  • 10

2 Answers2

1

A couple of things here. First of you have to distinguish between JPA and Bean Validation. Two different specifications and things. @Basic is a JPA annotation whereas @NotNull is a Bean Validation annotation. Using @Basic(optional=false) in conjunction with schema creation you will indeed get a database constraint which in turn lead to a JDBC exception during persist.

By introducing Bean Validation you activate the JPA integration of Bean Validation. In this case prior to writing to the database the data will be validated via Bean Validation. In this case as part of pre-persist. As per specification a ConstraintViolationException is thrown in this case. You can call ConstraintViolationException.getConstraintViolations to get a set of the failing constraints. It is up to you to catch this exception and do the unwrapping yourself.

Hardy
  • 18,659
  • 3
  • 49
  • 65
0

I'm looking for a method to display violations with out catching ConstraintViolations everywhere.

You could add a catch(ConstraintViolationException cve) {...} block at the outermost level of your application code (e.g. in form of some request handler/interceptor in case this is a web application) and use that to handle constraint violations in a generic way. The ConstraintViolation object provides lots of information such as the name of the concerned property etc. I'm not sure though why EclipseLink doesn't consider @Basic(optional=false), though.

Gunnar
  • 18,095
  • 1
  • 53
  • 73