Java – Confusion: @NotNull vs. @Column(nullable = false) with JPA and Hibernate

hibernatehibernate-annotationsjavajpapersistence

  1. When they appear on a field/getter of an @Entity, what is the difference between them? (I persist the Entity through Hibernate).

  2. What framework and/or specification each one of them belongs to?

  3. @NotNull is located within javax.validation.constraints. In the javax.validation.constraints.NotNull javadoc it says

    The annotated element must not be null

    but it does not speak of the element's representation in the database, so why would I add the constraint nullable=false to the column?

Best Answer

@NotNull is a JSR 303 Bean Validation annotation. It has nothing to do with database constraints itself. As Hibernate is the reference implementation of JSR 303, however, it intelligently picks up on these constraints and translates them into database constraints for you, so you get two for the price of one. @Column(nullable = false) is the JPA way of declaring a column to be not-null. I.e. the former is intended for validation and the latter for indicating database schema details. You're just getting some extra (and welcome!) help from Hibernate on the validation annotations.