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

James McMahon picture James McMahon · May 20, 2010 · Viewed 97.6k times · Source

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.

Answer

Pascal Thivent picture Pascal Thivent · May 20, 2010

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.