随着ORM框架的应用,使得开发更加面向对象,不用再专门设计数据库,由编写实体,实体映射代替。
所以,实体的编写是非常基础而重要的工作,开发工作能及早做就不要往后拖。比如,验证数据的合法性,我们习惯在action或者controller中做,其实这些工作可以提前在实体做的。
JSR303Bean Validator是数据验证的规范,而hibernate validator 是其中的一个实现。
比如在User实体中,可以使用Hibernate Validator 来对该实体模型进行验证
需要引入包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; } }
测试类,通过hibernate validator验证输入数据的合法性
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()); } }
打印异常信息
userName: 长度需要在1和32之间
userName: 不能为空
把hibernate简单用起来是很简单的,但是如果要进行调优,还是很复杂的。后文中会介绍在实体模型中加入hibernate缓存。