package com.mandi.common; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import com.mandi.dao.common.ObjectResult; /** * @author mengly * @version 创建时间:2016年6月3日 下午1:18:57 * 类说明 :hibernate validator */ public class ValidatorUtils { private static Validator validator=null; public static Validator getValidator() { if(validator==null) { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); validator=factory.getValidator(); } return validator; } public static Set> checkCTS(T t) { Validator v=ValidatorUtils.getValidator(); Set> cts=v.validate(t); return cts; } public static ObjectResult checkForMsgs(T t) { ObjectResult objr=new ObjectResult(); if(t==null) { objr.setCode(1); objr.setHint("对象为空!"); objr.setErrmsg("对象为空!"); return objr; } Validator v=ValidatorUtils.getValidator(); Set> cts=v.validate(t); if(cts.size()>0) { objr.setCode(1); Iterator> it=cts.iterator(); StringBuffer sb=new StringBuffer(); while(it.hasNext()) { ConstraintViolation ct=it.next(); sb.append(ct.getMessage()+";"); } objr.setHint(sb.toString()); objr.setErrmsg(sb.toString()); }else{ objr.setCode(0); } return objr; } public boolean check(T t) { Set> cts=checkCTS(t); if(cts.size()>0) { return false; }else{ return true; } } public static ObjectResult checkPro(T t,String[] Pros) { ObjectResult objr=new ObjectResult(); if(t==null) { objr.setCode(1); objr.setHint("对象为空!"); objr.setErrmsg("对象为空!"); return objr; } Validator v=ValidatorUtils.getValidator(); StringBuffer sb=new StringBuffer(); Set> cts=new HashSet>(); for (String pro:Pros) { cts=v.validateProperty(t,pro); if(cts.size()>0) { Iterator> it=cts.iterator(); while(it.hasNext()) { ConstraintViolation ct=it.next(); sb.append(ct.getMessage()+";"); } } } if(sb.length()>0) { objr.setCode(1); objr.setErrmsg(sb.toString()); }else objr.setCode(0); return objr; } }