javax.persistence @Column 上的长度字段是否定义了最大值? [英] Does the length field on the javax.persistence @Column define max?

查看:54
本文介绍了javax.persistence @Column 上的长度字段是否定义了最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

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

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

但是,数据库架构将列定义为长度为 13.当通过以下方式检索项目时:

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

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

serialNo 字符等于 13(因为 db table schema 允许 13)的数据仍然显示为 13,而不是被截断.@Column length 那么有什么用呢?

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?

推荐答案

javax.persistence.Columnlength属性用于定义String字段的列长度(其他类型忽略)并且在持久性框架将从实体生成数据库模式(几个CREATE TABLE)时使用,例如此选项(用于hibernate上的Hibernate.cfg.xml):

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>

在您的示例中,列 serialNo 将创建为 VARCHAR(12).

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.

这篇关于javax.persistence @Column 上的长度字段是否定义了最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆