Java自定义约束 - 如果isValid = true

时间:2016-01-25 14:15:38

标签: java validation

我试图实施@Unique约束,但我得到了一个我无法忍受的错误...

我的唯一课程是基础课程:

@Target({FIELD, METHOD})
@Retention(RUNTIME)
@Constraint(validatedBy = UniqueConstraintValidator.class)
public @interface Unique {

    String message() default "{}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    String property() default "id";

    Class<?> entity();

}

我以这种方式注释我的属性:

@NotNull
@Unique(entity = Luce.class, property="numeroLuce")
@Column(name="numero_luce")
public int getNumeroLuce() {
    return numeroLuce;
}

public void setNumeroLuce(int numeroLuce) {
    this.numeroLuce = numeroLuce;
}

然后,这是我的验证器。它可以返回属性已经存在的错误,但是,如果元素有效,则会出现异常

@Transactional
public class UniqueConstraintValidator implements ConstraintValidator<Unique, Serializable> {
    private static final Logger logger = Logger.getLogger(UniqueConstraintValidator.class);


    @Autowired
    private SessionFactory sessionFactory;



    protected Session getSession() {
        logger.debug("La sessione è " + sessionFactory.toString());
        return sessionFactory.getCurrentSession();
    }

    private Class<?> entityClass;
    private String uniqueField;
    private int currentValue;

    public void initialize(Unique unique) {
        entityClass = unique.entity();
        uniqueField = unique.property();

    }

    @SuppressWarnings("rawtypes")
    public boolean isValid(Serializable property, ConstraintValidatorContext cvContext) {

        String query = String.format("from %s where %s = :field ", entityClass.getName(), uniqueField);
        List list = getSession().createQuery(query).setParameter("field", property).list();
        int listSize = list.size();

        logger.debug("Session is: " + sessionFactory.toString());
        logger.debug("Condition is: " + list != null && listSize == 0);

//      return list != null && listSize == 0 && prova.equalsIgnoreCase(current);
        return list != null && listSize == 0;
        }


}

在有效的操作上,我得到了这个例外:

exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.validation.ValidationException: HV000028: Unexpected exception during isValid call.

引起:

java.lang.NullPointerException
    it.besmart.validator.UniqueConstraintValidator.getSession(UniqueConstraintValidator.java:30)
    it.besmart.validator.UniqueConstraintValidator.isValid(UniqueConstraintValidator.java:53)
    it.besmart.validator.UniqueConstraintValidator.isValid(UniqueConstraintValidator.java:1)
    org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:283)
    org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:133)
    org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:91)
    org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:83)
    org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:547)
    org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:487)
    org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:451)
    org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:403)
    org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:206)
    org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:137)
    org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreInsert(BeanValidationEventListener.java:95)
    org.hibernate.action.internal.EntityIdentityInsertAction.preInsert(EntityIdentityInsertAction.java:214)
    org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:92)
    org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:490)
    org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:195)
    org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:179)
    org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:214)
    org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
    org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
    org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
    org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
    org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)
    org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)
    org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
    org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)
    org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
    org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
    it.besmart.dao.AbstractDao.persist(AbstractDao.java:38)
    it.besmart.dao.LuceDaoImpl.saveLuci(LuceDaoImpl.java:49)
    it.besmart.service.LuceServiceImpl.saveLuci(LuceServiceImpl.java:35)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
.....

修改 我试图从我的AbstractDao获取当前会话,因此我将UniqueConstraintValidator.java类扩展到它。 我得到了同样的错误,但是现在来自AbstractDao的getSession是空的...即使在我的日志中它也不是......使用AbstractDao我用数据库进行所有交易,它们都运行良好,只有当我使用Unique i注释e字段时才会收到此错误...

java.lang.NullPointerException
it.besmart.dao.AbstractDao.getSession(AbstractDao.java:28)

0 个答案:

没有答案