Constraint validation and bean validation

2 posts / 0 new
Last post
Constraint validation and bean validation

I've seen that for a specific property, such as title from the Book class, two annotations are used to specify a not-null constraint: @Column( nullable = false) and @NotNull. Is this really necessarily or it is sufficient to use just one of them? And in case that one is sufficient, then, which one should we use?

Both annotations have to be used in this case

Both annotations have to be used for our/your specific example. The @Column( nullable = false) annotation, part of the JPA API, is used as a restriction for the database column associated with that specific (title in your example) class property, e.g., used when the database schema is generated. The @NotNull  annotation is part of the Java Validation API and it is used to validate (check not-null constraint) the property no matter if the related object is then saved to the database or not. Also, when using JSF for your web application, it is easy to catch the validation errors, and possibly display error messages, which results from the Validation API, e.g., @NotNull from your example.