問題描述
在 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.
同時提供 Size
和 length
似乎是多余的,但根據 附錄 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 注釋上設置長度屬性時有什么作用?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!