工具类
import io.renren.common.exception.RRException;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
public class ValidatorUtils {
private static Validator validator;
static {
validator = Validation.buildDefaultValidatorFactory().getValidator();
}
/**
* 校验对象
* @param object 待校验对象
* @param groups 待校验的组
* @throws RRException 校验不通过,则报RRException异常
*/
public static void validateEntity(Object object, Class<?>... groups)
throws RRException {
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
if (!constraintViolations.isEmpty()) {
StringBuilder msg = new StringBuilder();
for(ConstraintViolation<Object> constraint: constraintViolations){
msg.append(constraint.getMessage()).append(";");
}
throw new RRException(msg.toString());
}
}
}
实体
@TableName("base_match")
public class BaseMatchEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
@TableId
private Integer id;
/**
* 场馆名称
*/
@NotNull(message = "场馆不能为空")
private Integer venueId;
/**
* 场馆名称
*/
@NotBlank(message = "场馆名称不能为空")
private String venueName;
/**
* 比赛项目
*/
@NotBlank(message = "比赛项目不能为空")
private String projectName;
/**
* 比赛日期
*/
@NotNull(message = "比赛日期不能为空")
private String matchDate;
/**
* 开始时间
*/
@NotBlank(message = "开始时间不能为空")
private String beginTime;
/**
* 结束时间
*/
@NotBlank(message = "结束时间不能为空")
private String endTime;
/**
* 创建时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
/**
* 修改时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
}
校验
ValidatorUtils.validateEntity(baseMatchEntity );