How to use additional parameters inside ConstraintValidator.isValid method
-
Good afternoon! I'm trying to create a custom generic Bean Validator for the email of an author and the name of a category to verify that they are unique and I wish I could use a custom JPQL, the name of the persistence unit in persistence.xml and other variables. However, I don't know how to pass variables inside isValid, I only know how to hardcode them.
public class UniqueFieldValidator implements ConstraintValidator {
@Override
public boolean isValid(T value, ConstraintValidatorContext context)
{
EntityManagerFactory emf = Persistence.createEntityManagerFactory("project");
EntityManager em = emf.createEntityManager();String jpql = "select a from Author a where a.email = :pEmail"; TypedQuery query = em.createQuery(jpql, Author.class); query.setParameter("pEmail", value); Optional optAuthor = Optional.of(query.getSingleResult()); if(optAuthor.isPresent()) { return false; } return true;
}
} -
Good afternoon! I'm trying to create a custom generic Bean Validator for the email of an author and the name of a category to verify that they are unique and I wish I could use a custom JPQL, the name of the persistence unit in persistence.xml and other variables. However, I don't know how to pass variables inside isValid, I only know how to hardcode them.
public class UniqueFieldValidator implements ConstraintValidator {
@Override
public boolean isValid(T value, ConstraintValidatorContext context)
{
EntityManagerFactory emf = Persistence.createEntityManagerFactory("project");
EntityManager em = emf.createEntityManager();String jpql = "select a from Author a where a.email = :pEmail"; TypedQuery query = em.createQuery(jpql, Author.class); query.setParameter("pEmail", value); Optional optAuthor = Optional.of(query.getSingleResult()); if(optAuthor.isPresent()) { return false; } return true;
}
}Default Is Valid Implementation As Below public boolean isValid(Object value, ConstraintValidatorContext ctx)