我有一个服务方法试图用 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.service() for servlet [services] in context with path [] threw exception [Request processing failed; nested exception is javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'org.hibernate.validator.constraints.NotBlank' validating type 'java.lang.Boolean'. Check configuration for 'disabled'] with root cause javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'org.hibernate.validator.constraints.NotBlank' validating type 'java.lang.Boolean'. Check configuration for 'disabled'
我认为 to 和模型类之间的映射有问题,但是,为什么 get 方法有效而只有 store()
无效?解决方案是什么?
最佳答案
你应该使用 @NotNull
注释。
您的boolean
是原始类型,而不是对象类型(Boolean
)因此约束@NotNull
无法应用,因为原始类型不能为 null
。注释执行以下验证(我添加的格式):
The annotated element must not be
null
. Accepts any type.
使用对象类型:
@NotNull
@Column(name = "DISABLE", nullable = false)
private Boolean disabled;
关于Java hibernate 找不到 boolean 值的 validator ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53769165/