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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With