使用 JPA 和 Hibernate 时@Size、@Length 和 @Column(length=value) 的区别 [英] Difference between @Size, @Length and @Column(length=value) when using JPA and Hibernate
问题描述
下面三个字段的验证检查有什么区别?
What is the difference between the validation check of the following three fields?
@Entity
public class MyEntity {
@Column(name = "MY_FIELD_1", length=13)
private String myField1;
@Column(name = "MY_FIELD_2")
@Size(min = 13, max = 13)
private String myField2;
@Column(name = "MY_FIELD_3")
@Length(min = 13, max = 13)
private String myField3;
// getter & setter
}
我读到第一个与 DDL 相关.第二个是用于 bean 验证.第三个是用于休眠验证.
I read that the first one has to do with DDL stuff. The second is for bean-validation. The third is for hibernate-validation.
这样对吗?我仍然不明白的是:我什么时候必须使用哪一个?这些注释之一何时触发?
Is that correct? What I still don't understand is: When do I have to use which one? When does one of these annotations trigger?
考虑以下情况:鉴于需要开发一个长度为 13 的字符串类型字段的实体.您会选择上述哪种方法?或者甚至更好:您必须问自己哪些问题才能找出哪个问题适合您的目的?
Think of the following situation: Given the requirement to develope an entity with a field of type string with length 13. Which of above mentioned methods would you choose? Or even better: Which questions do you have to ask yourself to find out which one suits your purposes?
推荐答案
@Column
是一个 JPA 注释,模式生成工具使用length
属性来设置关联的 SQL 列长度.@Size
是一个 Bean Validation 注释,用于验证关联的 String 是否具有长度受最小值和最大值限制的值.@Length
是 Hibernate 特有的注解,与@Size
含义相同
@Column
is a JPA annotation and thelength
attribute is used by the schema generation tool to set the associated SQL column length.@Size
is a Bean Validation annotation that validates that the associated String has a value whose length is bounded by the minimum and maximum values.@Length
is a Hibernate-specific annotation and has the same meaning as@Size
所以 2.
和 3.
都应该使用 Bean Validation 来验证 String
的长度.我会选择 2.
因为它是通用的.
So both 2.
and 3.
should validate the String
length using Bean Validation. I'd pick 2.
because it's generic.
这篇关于使用 JPA 和 Hibernate 时@Size、@Length 和 @Column(length=value) 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!