Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the length attribute do when set on the @Column JPA annontation?

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.

like image 810
James McMahon Avatar asked May 20 '10 15:05

James McMahon


People also ask

What is the use of @column annotation?

@Column annotation is used for Adding the column the name in the table of a particular MySQL database.

What is columnDefinition in @column annotation?

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.

What is column length?

The length of the roadway occupied by a column or a convoy in movement. See also road space. Dictionary of Military and Associated Terms.

Is @column annotation mandatory?

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.


1 Answers

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.

like image 173
Pascal Thivent Avatar answered Sep 24 '22 02:09

Pascal Thivent