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

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

问题描述

我有这样的代码:

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

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






$ b然而,数据库模式将列定义为长度13.通过以下方式检索商品:

 列表< Item> items = getEntityManager()。createNamedQuery(SQL).getResultList(); 

具有 serialNo 个字符的数据等于 13 (因为db table schema允许13)仍然显示为13,不会被截断。什么是 @Column 长度然后?

解决方案

javax .persistence.Column 长度属性用于定义字符串字段(在其他类型时忽略),并且当持久性框架将生成数据库模式时,仅使用 (几个 CREATE TABLE (对于 hibernate.cfg.xml 中的Hibernate):

 < property name =hbm2ddl.auto>建立< / property> 

在你的例子中,列 serialNo 会创建为 VARCHAR(12)



为了所有其他目的(插入或检索数据) 忽略







此外,如果您想在您的课程中记录数据库的元数据信息。通过这种方式,自己可以在尝试插入和避免任何值太长数据截断之前验证待保存的值。例外。


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?

解决方案

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.

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

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