在 @Column JPA 注释上设置长度属性时有什么作用? [英] What does the length attribute do when set on the @Column JPA annontation?

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

问题描述

在 JPA 中设置列​​的长度到底有什么作用?

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;
}

我知道您可以使用注释来基于实体对象生成数据库架构 (DDL),但是长度是否会在持久性发生时进行任何类型的检查或截断,或者它仅用于架构创建?

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?

我还意识到 JPA 可以位于各种实现之上,在这种情况下我关注的实现是 Hibernate.

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?

Column注解用于指定:

The length attribute of the Column annotation is used to specify:

列长度.(仅在使用字符串值列时适用.)

The column length. (Applies only if a string-valued column is used.)

And 仅在生成的 DDL 中使用.在您的示例中,结果列将生成为 VARCHAR(32) 并且尝试插入更长的字符串会导致 SQL 错误.

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.

对于验证,您可以添加 @Size(max=32) 约束 来自 Bean Validation API (JSR 303).我在此处提供了一个可运行测试的示例.

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.

同时提供 Sizelength 似乎是多余的,但根据 附录 D. 的 Bean Validation 规范,生成 Bean Validation-aware DDL 对于 Persistence Providers 不是强制性的.所以使用 length 作为 DDL,@Size 进行验证.

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.

如果您有兴趣,只需将 Bean Validation 实现放在 JPA 2.0 的类路径上.对于 JPA 1.0,请参阅此previous answer.

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 注释上设置长度属性时有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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