Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of @Basic(optional = false) in writing entity class

Tags:

java

orm

jpa

Uhm, I have a question regarding the @Basic(optional = false) and @NotNull notation.

Usually, we would write variables in entity class as below:

Mock-up code:

@Basic(optional = false)
@NotNull
@Column(name = USERNAME)
private String userName;

The notation above describes that for the field username , it would not accept a NULL value.

Usually, the @Basic(optional = false) notation is followed by @NotNull notation , but if I would like to have a field, let's say userID , and it is an Auto-Increment type , which is also the Primary Key , should I just wrote the code as below?

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = USERID)
private Integer userID;

Or remove the @Basic(optional = false) as well?

Edited

Latest code:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = USERID)
private Integer userID;

One more question, is that only @Basic(optional = false) will work same as @Basic(optional = false) followed-up by @NotNull ?

Code shown as below:

Code 1

@Basic(optional = false)
@NotNull
@Column(name = USERNAME)
private String userName;

Code 2

@Basic(optional = false)
@Column(name = USERNAME)
private String userName;
like image 866
MMM Avatar asked Feb 12 '23 08:02

MMM


1 Answers

no. @Id replaces @Basic - either use one or the other. @GeneratedValue can only accompany @Id.

@NotNull has nothing to do with JPA and you can place it wherever you want.

more info on NotNull vs Column annotations - as explained in this question, NotNull and Column annotation properties come from different places (bean validation vs persistence) and deal with different aspects of the object's lifecycle:

@NotNull is a bean validation annotation that specifies that the property must hold some value. hibernate MAY check this before persisting your entity into the database, if hibernate-validator integration is enabled in your setup, but may also completely ignore it. various other frameworks along the way (jax-rs implementations in your API layer etc) may also check your bean to validate that @NotNull holds. hibernate may also take notice of this annotation when generating the database schema and make the column not nullable, but its in no way required to do so.

@Column is a JPA annotation and deals only with how your property is mapped to the database. nothing else. you can make a column not nullable and still pass a null value to hibernate. it will result in a runtime exception from the database when hibernate will try to insert/update your data, but hibernate will not check it in advance.

like image 141
radai Avatar answered Feb 15 '23 09:02

radai