1. 程式人生 > >hbiernate validator 校驗實體bean工具類

hbiernate validator 校驗實體bean工具類

因公司專案需要,我們需要在其他地方對實體類經行校驗,所有提取出來一個工具類ValidateUtil

public class ValidateUtil {

	/**
	 * 校驗實體類
	 * 
	 * @param t
	 * @return
	 */
	public static <T> List<Map<String, String>> validate(T t) {
		//定義返回錯誤List
		List<Map<String, String>> errList = new ArrayList<Map<String, String>>();

		Map<String, String> errorMap;
		
		ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
		
		Validator validator = factory.getValidator();

		Set<ConstraintViolation<T>> errorSet = validator.validate(t);

		for (ConstraintViolation<T> c : errorSet) {
			errorMap = new HashMap<>();
			errorMap.put("field", c.getPropertyPath().toString()); //獲取發生錯誤的字典名稱
			errorMap.put("msg", c.getMessage()); //獲取校驗資訊
			errList.add(errorMap);
		}

		return errList;
	}

}

呼叫

List<Map<String, String>> validate = ValidateUtil.validate(school);