4

Of the three options, should I be using one or two or all three combined to prevent null values?

@NotNull
@Column(name = "SOME_VALUE", nullable = false)
@Basic(optional = false)
private String someValue;

Note that I don't consider this a duplicate of an existing question. I see many questions that ask about a subset of these three options but have yet to find one that asks about which of the three is appropriate to use in a modern JPA/Hibernate stack.

Community
  • 1
  • 1
Chris Williams
  • 11,647
  • 15
  • 60
  • 97
  • 1
    Possible duplicate of [Confusion: @NotNull vs @Column(nullable = false)](http://stackoverflow.com/questions/7439504/confusion-notnull-vs-columnnullable-false) – Zeus Mar 31 '17 at 17:23
  • 1
    @Zeus, I already explained why I think this is NOT a dupe of that exact question. – Chris Williams Mar 31 '17 at 17:55
  • 1
    If you are using a validator, then `@NotNull` will generate an exception before a query is made. If you are using `@Column(nullable = false)` and you are generating the tables using JPA, you will get an exception upon insert/update. `@Basic(optional = false)` is also used during schema generation, so the exception will be generated upon insert/update due to constraint violation, same as with `@Column(nullable = false)`. In general automated validation results in less-meaningful error messages than desired, so you might want to do it manually. – coladict Apr 03 '17 at 07:27

1 Answers1

5

@NotNull

  1. Belongs to javax.validation.constraints package.
  2. As part of schema creation, not null constraint is created on DB column.
  3. Is handled by validation engine(VE).

  4. If a property is not set(or set to null), while persisting, VE throws an exception.

  5. As property validation is handled by a VE, useful in non-persistence layers such as UI layer(JSF).

@Basic(optional=false)

  1. Belongs to javax.persistence package.
  2. As part of schema creation, not null constraint is created on DB column.
  3. Is handled by persistence provider(PP).
  4. If a property is not set(or set to null) while persisting, the PP does not pass statement to DB; it throws an exception.

@Column(nullable=false)

  1. Belongs to javax.persistence package.
  2. As part of schema creation, not null constraint is created on DB column.
  3. Is handled by persistence provider(PP).
  4. If a property is not set(or set to null) while persisting, the PP does not pass statement to DB; it throws an exception.
  5. Allows to specify addtional parameters like column name(which can be different from property name).
lupchiazoem
  • 8,026
  • 6
  • 36
  • 42
  • 1
    What about `@ManyToOne(optional = false)`. Does it follow the same rules as those listed for `@Basic(optional=false)`? – T3rm1 Aug 12 '22 at 15:19