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

查看:34
本文介绍了在 @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),但是当持久化发生时 length 是否会进行任何类型的检查或截断,或者它仅用于架构创建?

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?

<的长度属性code>Column注解用于指定:

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

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

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

并且仅在生成的 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 验证 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 验证规范,生成 Bean 验证感知 DDL 对于持久性提供程序不是强制性的.所以使用 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.

如果您有兴趣,只需使用 JPA 2.0 在类路径上放置一个 Bean 验证实现.对于 JPA 1.0,请参阅此以前的答案.

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天全站免登陆