CriteriaQuery .where() for multiple conditions

#1

When using the below, there appears to be an OR condition:
 

 criteriaQuery.where(criteriaBuilder.equal(root.get("name"), name));
 criteriaQuery.where(criteriaBuilder.equal(root.get("surname"), surname));
 List<Person> allPersons = query.getResultList();

The results will contain records where name is equal to the given name OR surname is equal to the given surname. Is it possible to make it an AND condition instead so that it will only contain records with both name AND surname as specified?

I have tried the below and it works but not sure if it's the best way to do it or not?

public Person read(String name, String surname, ServletContext servletContext) {
        EntityManagerFactory emf = (EntityManagerFactory) servletContext.getAttribute("emf");
        EntityManager em = emf.createEntityManager();
        Person person;
        try {
            em.getTransaction().begin();
            CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
            CriteriaQuery
   
   
    
     criteriaQuery = criteriaBuilder.createQuery(Person.class);
            Root
    
    
      root = criteriaQuery.from(Person.class); criteriaQuery.select(root); Predicate criteria = criteriaBuilder.and(criteriaBuilder.equal(root.get("name"), name), criteriaBuilder.equal(root.get("surname"), surname)); criteriaQuery.where(criteria); person = em.createQuery(criteriaQuery).getSingleResult(); em.getTransaction().commit(); } finally { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } return person; } 
    
   
   
#2

Yes, it looks fine.

You may also check the result query string (JPQL) by toString() on the criteria query.

ObjectDB Support
ObjectDB - Fast Object Database for Java (JPA/JDO)

Post Reply

To post a reply and/or subscribe to update notifications - please login