Hibernate-Validation的使用

首先是要加入下面两个包

hibernate-validator-4.1.0.Final.jar
 validation-api-1.0.0.GA.jar

如果在验证不通过的时候进行了添加、更新或删除操作的时候,则会抛出javax.validation.ConstraintViolationException异常

下面是测试用的类

Model2:

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.ManyToOne;

import javax.persistence.Table;

import javax.persistence.TableGenerator;

import javax.validation.Valid;

import javax.validation.constraints.Max;

import javax.validation.constraints.Min;

import javax.validation.constraints.NotNull;

import javax.validation.constraints.Size;



import org.hibernate.validator.constraints.Email;

import org.hibernate.validator.constraints.URL;



@Entity

@Table(name="t_Model2")

@TableGenerator(name="mytable",initialValue=1,allocationSize=1)

public class Model2 {



    private int id;

    private String name;

    private String address;

    private String phoneNumber;

    private String email;

    private int age;

    private Model3 model3;

    private String url;



    @Id

    @GeneratedValue(generator="mytable",strategy=GenerationType.TABLE)

    public int getId() {

        return id;

    }



    public void setId(int id) {

        this.id = id;

    }



    @NotNull(message="姓名不能为空!")

    public String getName() {

        return name;

    }



    public void setName(String name) {

        this.name = name;

    }



    @NotNull(message="地址不能为空!")

    public String getAddress() {

        return address;

    }



    public void setAddress(String address) {

        this.address = address;

    }



    @Size(max=11,min=11,message="长度只能为11位!")

    public String getPhoneNumber() {

        return phoneNumber;

    }



    public void setPhoneNumber(String phoneNumber) {

        this.phoneNumber = phoneNumber;

    }



    @Email(message="email地址无效!")

    @NotNull(message="email地址不能为空!")

    public String getEmail() {

        return email;

    }



    public void setEmail(String email) {

        this.email = email;

    }



    @NotNull(message = "Model3不能为空!")

    @Valid

    @ManyToOne

    public Model3 getModel3() {

        return model3;

    }



    public void setModel3(Model3 model3) {

        this.model3 = model3;

    }



    @Min(value=18,message="必须年满18岁!")

    @Max(value=30,message="年龄不能大于30岁!")

    public int getAge() {

        return age;

    }



    public void setAge(int age) {

        this.age = age;

    }



    @URL(message="无效的URL地址")

    @NotNull(message = "URL不能为空!")

    public String getUrl() {

        return url;

    }



    public void setUrl(String url) {

        this.url = url;

    }

    

}

 Model3:

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

import javax.persistence.Table;

import javax.validation.constraints.NotNull;



@Entity

@Table(name="t_Model3")

public class Model3 {



    private int id;

    

    private String name;



    @Id

    @GeneratedValue

    public int getId() {

        return id;

    }



    public void setId(int id) {

        this.id = id;

    }



    @NotNull(message="model3的名称不能为空!")

    public String getName() {

        return name;

    }



    public void setName(String name) {

        this.name = name;

    }

    

}

Test类:

import org.springframework.context.ApplicationContext;



import com.tiantian.test.model.Model2;

import com.tiantian.test.service.Model2Service;

import com.tiantian.test20110430.util.Util;



public class Test1 {



    public static void main(String args[]) {

        ApplicationContext context = Util.getContext();

        Model2Service service = context.getBean(Model2Service.class);

        Model2 model = new Model2();

        model.setName("hello");

        model.setEmail("[email protected]");

        model.setAddress("湖南长沙");

        model.setPhoneNumber("15012345678");



        String result = Util.validateModel(model);// 返回的验证结果,验证结果就是一个字符串,如果有错误的话则该字符串的长度大于0

        System.out.println(result);

        if (result.length() == 0)// 验证不通过的时候就不添加

            service.add(model);

    }

}

上面用到的Util类:

import java.util.Iterator;

import java.util.Set;



import javax.validation.ConstraintViolation;

import javax.validation.Validation;

import javax.validation.Validator;



import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;



public class Util {



    private static ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

    

    public static ApplicationContext getContext() {

        return context;

    }

    

    public static String validateModel(Object obj) {//验证某一个对象

        

        StringBuffer buffer = new StringBuffer(64);//用于存储验证后的错误信息

        

        Validator validator = Validation.buildDefaultValidatorFactory()

                .getValidator();



        Set<ConstraintViolation<Object>> constraintViolations = validator

                .validate(obj);//验证某个对象,,其实也可以只验证其中的某一个属性的



        Iterator<ConstraintViolation<Object>> iter = constraintViolations

                .iterator();

        while (iter.hasNext()) {

            String message = iter.next().getMessage();

            buffer.append(message);

        }

        return buffer.toString();

    }    

}

下面是一些主要的注解:

 1         @AssertTrue //用于boolean字段,该字段只能为true

 2         @AssertFalse//该字段的值只能为false

 3         @CreditCardNumber//对信用卡号进行一个大致的验证

 4         @DecimalMax//只能小于或等于该值

 5         @DecimalMin//只能大于或等于该值

 6         @Digits(integer=2,fraction=20)//检查是否是一种数字的整数、分数,小数位数的数字。

 7         @Email//检查是否是一个有效的email地址

 8         @Future//检查该字段的日期是否是属于将来的日期

 9         @Length(min=,max=)//检查所属的字段的长度是否在min和max之间,只能用于字符串

10         @Max//该字段的值只能小于或等于该值

11         @Min//该字段的值只能大于或等于该值

12         @NotNull//不能为null

13         @NotBlank//不能为空,检查时会将空格忽略

14         @NotEmpty//不能为空,这里的空是指空字符串

15         @Null//检查该字段为空

16         @Past//检查该字段的日期是在过去

17         @Size(min=, max=)//检查该字段的size是否在min和max之间,可以是字符串、数组、集合、Map等

18         @URL(protocol=,host,port)//检查是否是一个有效的URL,如果提供了protocol,host等,则该URL还需满足提供的条件

19         @Valid//该注解只要用于字段为一个包含其他对象的集合或map或数组的字段,或该字段直接为一个其他对象的引用,

20                 //这样在检查当前对象的同时也会检查该字段所引用的对象

 

 

你可能感兴趣的:(validation)