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;
}
}