257 words

CriteriaQuery .where() for multiple conditions

#1
2014-08-10 16:02

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
   <person>
     criteriaQuery = criteriaBuilder.createQuery(Person.class);
            Root
    <person>
      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; } 
    </person>
   </person>
ThreaT
ThreaT's picture
Joined on 2014-02-19
User Post #25
#2
2014-08-10 21:40

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)
support
support's picture
Joined on 2010-05-03
User Post #2,016

Post Reply

Please read carefully the posting instructions - before posting to the ObjectDB website.

  • You may have to disable pop up blocking in order to use the toolbar (e.g. in Chrome).
  • Use ctrl + right click to open the browser context menu in the editing area (e.g. for using a browser spell checker).
  • To insert formatted lines (e.g. Java code, stack trace) - select a style in the toolbar and then insert the text in the new created block.
  • Avoid overflow of published source code examples by breaking long lines.
  • You may mark in paragraph code words (e.g. class names) with the code style (can be applied by ctrl + D).
  • Long stack traces (> 50 lines) and complex source examples (> 100 lines) should be posted as attachments.
Attachments:
Maximum file size: 32 MB
Cancel