Java 使用 JPA 和 Hibernate 时 @Size、@Length 和 @Column(length=value) 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34588354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:48:56  来源:igfitidea点击:

Difference between @Size, @Length and @Column(length=value) when using JPA and Hibernate

javahibernatevalidationjpaorm

提问by Chris311

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

}

I read that the first one has to do with DDL stuff. The second is for bean-validation. The third is for hibernate-validation.

我读到第一个与 DDL 相关。第二个是用于 bean 验证。第三个是用于休眠验证。

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?

那是对的吗?我仍然不明白的是:我什么时候必须使用哪一个?这些注释之一何时触发?

Edit: 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?

编辑:考虑以下情况:假设需要开发一个长度为 13 的字符串类型字段的实体。您会选择上述哪种方法?或者甚至更好:您必须问自己哪些问题才能找出哪个问题适合您的目的?

采纳答案by Vlad Mihalcea

  1. @Columnis a JPA annotation and the lengthattribute is used by the schema generation tool to set the associated SQL column length.
  2. @Sizeis a Bean Validation annotation that validates that the associated String has a value whose length is bounded by the minimum and maximum values.
  3. @Lengthis a Hibernate-specific annotation and has the same meaning as @Size
  1. @Column是一个 JPA 注释,length模式生成工具使用该属性来设置关联的 SQL 列长度。
  2. @Size是一个 Bean Validation 注释,用于验证关联的 String 是否具有长度受最小值和最大值限制的值。
  3. @Length是一个 Hibernate 特定的注解,与 @Size

So both 2.and 3.should validate the Stringlength using Bean Validation. I'd pick 2.because it's generic.

因此,无论2.并且3.应该验证String使用Bean验证长度。我会选择2.因为它是通用的。