Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

java - 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

}

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?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. @Column is a JPA annotation and the length attribute is used by the schema generation tool to set the associated SQL column length.
  2. @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.
  3. @Length is a Hibernate-specific annotation and has the same meaning as @Size

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...