What is the difference between the validation check of the following three fields?
@Entity
public class MyEntity {
@Column(name = "MY_FIELD_1", length=13)
private String myField1;
@Column(name = "MY_FIELD_2")
@Size(min = 13, max = 13)
private String myField2;
@Column(name = "MY_FIELD_3")
@Length(min = 13, max = 13)
private String myField3;
// getter & setter
}
I read that the first one has to do with DDL stuff. The second is for bean-validation. The third is for hibernate-validation.
Is that correct? What I still don't understand is: When do I have to use which one? When does one of these annotations trigger?
Edit: Think of the following situation: Given the requirement to develope an entity with a field of type string with length 13. Which of above mentioned methods would you choose? Or even better: Which questions do you have to ask yourself to find out which one suits your purposes?
The @Column annotation is defined as a part of the Java Persistence API specification. It's used mainly in the DDL schema metadata generation. This means that if we let Hibernate generate the database schema automatically, it applies the not null constraint to the particular database column.
In this article, we will discuss how to change the column name in the Spring project using JPA. @Column annotation is used for Adding the column the name in the table of a particular MySQL database. Syntax: @Column(name=”DESC”, nullable=false, length=512)
@Column. Let's start with the @Column annotation. It is an optional annotation that enables you to customize the mapping between the entity attribute and the database column.
columnDefinition definition: The SQL fragment that is used when generating the DDL for the column. columnDefinition default: Generated SQL to create a column of the inferred type.
@Column
is a JPA annotation and the length
attribute is used by the schema generation tool to set the associated SQL column length.@Size
is a Bean Validation annotation that validates that the associated String has a value whose length is bounded by the minimum and maximum values.@Length
is a Hibernate-specific annotation and has the same meaning as @Size
So both 2.
and 3.
should validate the String
length using Bean Validation. I'd pick 2.
because it's generic.
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