With the application of the orm framework, development is more object-oriented, and there is no need to design a database specifically, instead of writing entities and object ing.
Therefore, entity writing is a very basic and important task. Do not drag your development work back when you do it. For example, to verify the validity of data, we are used to doing it in action or controller. In fact, this work can be done in advance in entity.
JSR303BeanValidator is a data verification specification, while hibernate validator is an implementation.
For example, in the User object, you can use Hibernate Validator to verify the object model.
Need to introduce package validation-api-1.0.0.GA.jar, hibernate-validator-4.0.0.GA.jar
importjavax.persistence.Column;importjavax.persistence.Entity;importjavax.persistence.GeneratedValue;importjavax.persistence.Id;importjavax.persistence.Table; importorg.hibernate.annotations.GenericGenerator;importorg.hibernate.validator.constraints.Length;importorg.hibernate.validator.constraints.NotBlank; @Entity@Table(name="t_user")public class User { @Id @GeneratedValue(generator ="system-uuid") @GenericGenerator(name ="system-uuid", strategy = "uuid") @Column(length=32)privateString id; @NotBlank@Length(min=1,max=32)@Column(nullable=false,length=32, unique=true, updatable=false)privateString userName; @Column(length=32)privateString age; publicString getId() {returnid;} publicvoid setId(String id) {this.id= id;} publicString getUserName() {returnuserName;} publicvoid setUserName(String userName) {this.userName= userName;} publicString getAge() {returnage;} publicvoid setAge(String age) {this.age= age;}}
Test class: verifies validity of input data through hibernatevalidator
importjavax.validation.ConstraintViolation;importjavax.validation.Validation;importjavax.validation.Validator;importjavax.validation.ValidatorFactory; public static void main(String[] args) {ValidatorFactoryfactory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); User user = new User(); user.setUserName(""); user.setAge("23"); Set<ConstraintViolation<User>>constraintViolations =validator.validate(user);for(ConstraintViolation<User> constraintViolation : constraintViolations) { System.out.print(constraintViolation.getPropertyPath() + ": "); System.err.println(constraintViolation.getMessage()); }}
Print exception information
UserName: The length must be between 1 and 32.
UserName: cannot be blank
It is very easy to use hibernate, but it is still very complicated to optimize it. Later, we will introduce how to add the hibernate cache to the object model.