問(wèn)題描述
在 JPA 中設(shè)置列??的長(zhǎng)度到底有什么作用?
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;
}
我知道您可以使用注釋來(lái)基于實(shí)體對(duì)象生成數(shù)據(jù)庫(kù)架構(gòu) (DDL),但是長(zhǎng)度是否會(huì)在持久性發(fā)生時(shí)進(jìn)行任何類(lèi)型的檢查或截?cái)?,或者它僅用于架構(gòu)創(chuàng)建?
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?
我還意識(shí)到 JPA 可以位于各種實(shí)現(xiàn)之上,在這種情況下我關(guān)注的實(shí)現(xiàn)是 Hibernate.
I also realize that JPA can sit on top of various implementations, the implementation I am concerned with in this case is Hibernate.
推薦答案
當(dāng)持久性發(fā)生時(shí),長(zhǎng)度是否會(huì)進(jìn)行任何類(lèi)型的檢查或截?cái)啵蛘咚鼉H用于創(chuàng)建模式?
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:
列長(zhǎng)度.(僅在使用字符串值列時(shí)適用.)
The column length. (Applies only if a string-valued column is used.)
And 僅在生成的 DDL 中使用.在您的示例中,結(jié)果列將生成為 VARCHAR(32)
并且嘗試插入更長(zhǎng)的字符串會(huì)導(dǎo)致 SQL 錯(cuò)誤.
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.
對(duì)于驗(yàn)證,您可以添加 @Size(max=32)
約束 來(lái)自 Bean Validation API (JSR 303).我在此處提供了一個(gè)可運(yùn)行測(cè)試的示例.
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.
同時(shí)提供 Size
和 length
似乎是多余的,但根據(jù) 附錄 D. 的 Bean Validation 規(guī)范,生成 Bean Validation-aware DDL 對(duì)于 Persistence Providers 不是強(qiáng)制性的.所以使用 length
作為 DDL,@Size
進(jìn)行驗(yàn)證.
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 實(shí)現(xiàn)放在 JPA 2.0 的類(lèi)路徑上.對(duì)于 JPA 1.0,請(qǐng)參閱此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.
這篇關(guān)于在 @Column JPA 注釋上設(shè)置長(zhǎng)度屬性時(shí)有什么作用?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!