是什么在@Column JPA annontation设置当长度属性呢? [英] What does the length attribute do when set on the @Column JPA annontation?

查看:1430
本文介绍了是什么在@Column JPA annontation设置当长度属性呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

究竟设置列上的长度JPA做什么呢?

  @Column(NAME =middle_name,可为空=假,长度= 32)
公共字符串getMiddleName(){
    返回this.middleName;
}

据我所知,您可以使用标注生成基于实体对象的数据库架构(DDL),但长度做任何类型的支票或截断时持续性发生,或仅用于创建模式?

我也意识到,JPA可以坐在各种实现之上,我在这种情况下,我关心的是实现休眠。


解决方案

  

长度是否做任何形式的支票或截断时,会发生持续性,或者仅用于创建模式?


的<一个href=\"http://java.sun.com/javaee/5/docs/api/javax/persistence/Column.html#length%28%29\"><$c$c>length 属性 标注用于指定:


  

列长度。 (仅适用于使用字符串值的列。)


和只在生成的DDL使用。在你的榜样,结果列将作为生成一个 VARCHAR(32)并试图插入更长的字符串会导致SQL错误。


有关验证,您可以添加一个 @Size(最大值= 32) constraint从Bean验证API( JSR 303 )。我可运行的测试提供了一个示例<一个href=\"http://stackoverflow.com/questions/2725111/hibernate-onetoone-notnull/2726224#2726224\">here.

提供了两个尺寸长度看起来是多余的,但根据的Appendix D. 中的Bean验证规范,发电Bean验证感知DDL不是强制的持久性提供。因此,使用长度的DDL, @Size 进行验证。

如果你有兴趣,只是把使用JPA 2.0的类路径中的Bean验证实现。随着JPA 1.0,请参阅本<一个href=\"http://stackoverflow.com/questions/2410074/using-hibernate-validator-with-jpa-and-spring/2410160#2410160\">$p$pvious回答。

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.

解决方案

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.

这篇关于是什么在@Column JPA annontation设置当长度属性呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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