What exactly does setting the length on a column do in JPA?
@Column(name = "middle_name", nullable = false, length = 32) public String getMiddleName() { return this.middleName; }
I understand that you can use the annotations to generate the database schema (DDL) based on the entity objects, but does length do any sort of check or truncation when persistence happens, or it solely used for schema creation?
I also realize that JPA can sit on top of various implementations, the implementation I am concerned with in this case is Hibernate.
@Column annotation is used for Adding the column the name in the table of a particular MySQL database.
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.
The length of the roadway occupied by a column or a convoy in movement. See also road space. Dictionary of Military and Associated Terms.
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.
Does length do any sort of check or truncation when persistence happens, or it solely used for schema creation?
The length
attribute of the Column
annotation is used to specify:
The column length. (Applies only if a string-valued column is used.)
And is only used in the generated DDL. In your example, the resulting column would be generated as a VARCHAR(32)
and trying to insert a longer string would result in an SQL error.
For validation, you could add a @Size(max=32)
constraint from the Bean Validation API (JSR 303). I provided a sample with a runnable test here.
Providing both Size
and length
may seem redundant but according to the Appendix D. of the Bean Validation spec, generating Bean Validation-aware DDL is not mandatory for Persistence Providers. So use length
for the DDL, @Size
for validation.
In case you're interested, just put a Bean Validation implementation on the classpath with JPA 2.0. With JPA 1.0, refer to this previous answer.
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