我想创建一个自定义验证程序,以检查值是否唯一,但我得到NullPointerExcption
,因为未注入session
(以及任何其他@Autowired
字段) 。请解释一下我在这里缺少的东西。
自定义约束注释:
@Constraint(validatedBy = { UniqueUserValidator.class })
@Target({ FIELD, METHOD })
@Retention(RUNTIME)
public @interface Unique {
String message() default "Value is not unique!";
Class<?> entityType();
String property();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@Target({ TYPE })
@Retention(RUNTIME)
@interface List {
Unique[] value();
}
}
自定义验证程序类:
@Component
public class UniqueUserValidator implements ConstraintValidator<Unique, Object> {
private Unique unique;
@PersistenceContext
private Session session;
@Override
public void initialize(Unique unique) {
this.unique = unique;
}
@Transactional(rollbackFor = Exception.class, readOnly = true)
@Override
public boolean isValid(Object fieldValue, ConstraintValidatorContext constraintValidatorContext) {
return session
.createQuery("from " + unique.entityType().getSimpleName() +
" where " + unique.property() + "=" + fieldValue)
.getResultList()
.isEmpty();
}
}
持久性配置:
@Configuration
@EnableTransactionManagement
public class DataConfig {
@Bean
public JpaTransactionManager transactionManager() {
...
return jpaTransactionManager;
}
@Bean
public LocalSessionFactoryBean sessionFactory() {
...
return sessionFactory;
}
@Bean
public DataSource dataSource() {
...
return dataSource;
}
}
答案 0 :(得分:1)
所以,我找到了一个解决方案:
1.Declare验证器bean
@Bean
public Validator validator() {
return new LocalValidatorFactoryBean();
}
2.将其添加到LocalSessionFactoryBean
Properties customValidator = new Properties();
customValidator.put("javax.persistence.validation.factory", validator());
sessionFactory.setHibernateProperties(customValidator);