在自定义验证器Spring Hibernate

时间:2017-09-28 19:17:51

标签: java spring hibernate

我想创建一个自定义验证程序,以检查值是否唯一,但我得到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;
   }
}

1 个答案:

答案 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);