Does the length field on the javax.persistence @Column define max?
Asked Answered
U

1

9

I have this code:

public class Item { 
    @Column(name = "serialNo", length = 12)
    public String getSerialNo() {
        return this.serialNo;
    }

    public void setSerialNo(String serialNo) {
        this.serialNo = serialNo;
    }
}

However, the database schema defines the column to be lenght 13. When the item is retrieved via:

List<Item> items = getEntityManager().createNamedQuery(SQL).getResultList();

The data that has serialNo characters equal to 13 (since db table schema allows 13) are still being displayed as 13, not truncated. What is the use of the @Column length then?

Urogenital answered 17/5, 2013 at 0:42 Comment(0)
S
14

The javax.persistence.Column's length attribute is used to define the column length of String fields (it is ignored for other types) and is only used when the persistence framework will generate the database schema (several CREATE TABLEs) from the entities, such as this option (for Hibernate on hibernate.cfg.xml):

<property name="hbm2ddl.auto">create</property>

In your example, the column serialNo would be created as a VARCHAR(12).

For all other purposes (inserting or retrieving data), it is ignored.



Also, it is useful if you want to "document" metadata information of your database in your classes. This way, yourself can validate the to-be-saved value before trying to insert and avoid any "value too long" or "data truncation"-like exceptions.

Skinhead answered 17/5, 2013 at 1:15 Comment(3)
Can you paste the link to the documentation about that? This links says nothing about length used only for DDL: docs.oracle.com/javaee/5/api/javax/persistence/…Coco
Yeah, it is not too specific about that. Look at the spec (download.oracle.com/otndocs/jcp/persistence-2_1-fr-eval-spec/… - JavaPersistence.pdf), section 11.2.2.1. That's the only moment they mention length in the whole document.Skinhead
Clearly mentioned related to schema generation: "11.2 Object/Relational Metadata Used in Schema Generation". Thanks for replying.Coco

© 2022 - 2024 — McMap. All rights reserved.