JPQL is JPA’s object-oriented query language. It expresses queries in terms of persistent entity classes and their properties rather than database tables and columns, while retaining an SQL-like syntax. section 1.3 section 2.3.3
Use JPQL with these distinctions in mind:
- Refer to the persistent class name, such as Message, not necessarily its mapped table name; class names are case-sensitive. section 2.3.3
- Create JPQL through EntityManager and execute it within transaction boundaries, including read operations shown with Hibernate OGM. section 18.2.3
- Keep query code independent of a relational database’s SQL dialect, and use the same JPA query style with supported NoSQL backends. section 18.2.3
Ordering bids with JPQL
A typed query can select every Bid entity and order results by an entity property: EntityManager.createQuery("SELECT b FROM Bid b ORDER BY b.amount DESC", Bid.class).getResultList(). The query refers to Bid and amount, not a database table and column. A similar query, "SELECT i FROM Item i", retrieves a single Item entity.
Listing 18.10 Querying the MongoDB database using JPQL
Path: Ch18/hibernate-ogm/src/test/java/com/manning/javapersistence /hibernateogm/HibernateOGMTest.java @Test void testJPQLQuery() { EntityManager entityManager = #1 entityManagerFactory.createEntityManager(); #1 try { entityManager.getTransaction().begin(); #2 List<Bid> bids = entityManager.createQuery( #3 "SELECT b FROM Bid b ORDER BY b.amount DESC", Bid.class) #3 .getResultList(); #3 Item item = entityManager.createQuery( #4 "SELECT i FROM Item i", Item.class) #4 .getSingleResult(); #4 User user = entityManager.createQuery( #5 "SELECT u FROM User u", User.class).getSingleResult(); #5 assertAll(() -> assertEquals(2, bids.size()), #6 () -> assertEquals(new BigDecimal(2000), #6 bids.get(0).getAmount()), #6 () -> assertEquals(new BigDecimal(1000), #6 bids.get(1).getAmount()), #6 () -> assertEquals("Item1", item.getName()), #6 () -> assertEquals("John", user.getFirstName()), #6 () -> assertEquals("Smith", user.getLastName()) #6 ); entityManager.getTransaction().commit(); #7 } finally { entityManager.close(); #8 } } #1 Create an <kbd>EntityManager</kbd> with the help of the existing <kbd>EntityManagerFactory</kbd>. #2 Start a transaction; the operations need to be transactional. #3 Create a JPQL query to get all <kbd>Bid</kbd>s from the database, in descending order of <kbd>amount</kbd>. #4 Create a JPQL query to get the <kbd>Item</kbd> from the database. #5 Create a JPQL query to get the <kbd>User</kbd> from the database. #6 Check that the information obtained through JPQL contains what we previously persisted. #7 Commit the previously started transaction. #8 Close the previously created <kbd>EntityManager</kbd>.
Inspect the complete JPQL test listing, including EntityManager creation, transaction handling, typed queries, ordering, and result retrieval. section 18.2.3

