我有一个服务方法,它试图用hibernate的store()
方法添加一个对象。get方法对这个DAO和服务类有效,而添加则无效。控制台中没有错误。
UrlWhiteListDaoImpl urlDao;
MapperFacade mapper;
@Autowired
public UrlWhiteListingServiceImpl(UrlWhiteListDao urlWhiteListDao, MapperFacade mapper, UrlWhiteListDaoImpl urlDao) {
this.urlDao = urlDao;
this.urlWhiteListDao = urlWhiteListDao;
this.mapper = mapper;
}
@Override
public UrlWhiteListDto addUrlWhiteListItem(UrlWhiteListDto urlWhiteListDto) throws Exception {
String domainUrlToBeAdded = parseUrl(urlWhiteListDto.getDomain());
if (isDomainExistbyName(domainUrlToBeAdded)) {
throw new Exception("Already existed domain is tried to be added");
}
UrlWhitelist urlModel = mapper.map(urlWhiteListDto,UrlWhitelist.class);
urlDao.store(urlModel);
return urlWhiteListDto;
}
我的模型类是:
@Entity
@Table(name = UrlWhitelist.TABLE_NAME)
public class UrlWhitelist implements EntityBean {
public static final String TABLE_NAME = "URL_WHITE_LIST";
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID", nullable = false)
private Long id;
@NotBlank
@Column(name = "DOMAIN", nullable = false)
private String domain;
@NotBlank
@Column(name = "DISABLE", nullable = false)
private boolean disabled;
// getters & setters omitted
}
DAO实现类为:
public class UrlWhiteListDaoImpl extends EntityDaoImpl<UrlWhitelist, Long> implements UrlWhiteListDao {
protected UrlWhiteListDaoImpl() {
super(UrlWhitelist.class);
}
@Override
public List<UrlWhitelist> getByDomainName(String name) {
DetachedCriteria criteria = DetachedCriteria.forClass(UrlWhitelist.class);
criteria.add(Restrictions.eq("domain", name));
return getAllByCriteria(criteria);
}
}
在控制台中没有错误,但在服务器日志中显示:
SEVERE:路径为[]的上下文中Servlet[services]的Servlet.service((引发异常[请求处理失败;嵌套异常为javax.validation。意外类型异常:HV000030:找不到约束"org.hibernate.validator.constraints.NotBlank"验证类型"java.lang.Boolean"的验证程序。检查配置是否为"disabled"]javax.validation.ExpectedTypeException:HV000030:找不到约束"org.hibernate.validator.constraints.NotBlank"验证类型"java.lang.Boolean"的验证器。检查配置中是否存在"disabled">
我认为到和模型类之间的映射有问题,但是,为什么get方法有效,而只有store()
无效?解决方案是什么?
您应该使用@NotNull
注释。
您的boolean
是基元类型,而不是对象类型(Boolean
(,因此不能应用约束@NotNull
,因为基元类型不能是null
。注释执行以下验证(由我添加格式(:
带注释的元素不能是
null
。接受任何类型。
使用对象类型:
@NotNull
@Column(name = "DISABLE", nullable = false)
private Boolean disabled;
要解决此错误,必须使用正确的注释。在上面的问题中,@NotBlank
注释必须仅应用于任何String字段。
要验证布尔类型字段,请使用注释@NotNull
或使用Boolean
装箱类型
If(Boolean.TRUE.equals(disabled)){
//If you check this type of any Boolean value then check null value and also false both field}