Chris Williams
Chris Williams

Reputation: 12481

@Basic(optional = false) vs @Column(nullable = false) vs @NotNull

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.

Upvotes: 5

Views: 2394

Answers (1)

lupchiazoem
lupchiazoem

Reputation: 8086

@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).

Upvotes: 6

Related Questions