In addition to the JPQL, you still can use native SQL queries within the JPA framework. There will be many cases where you cannot achieve your goal using the JPQL, especially when you are required to use some DBMS-specific syntax, or when you are to perform very complex queries that you cannot perform using the built-in JPQL.
In the following code, we are going to show how to perform native queries using JPA APIs:
Query q = entityManager.createNativeQuery("SELECT m.title, m.producer FROM Movie m"); List<Object[]> movies = q.getResultList(); for (Object[] arr : movies) { System.out.println("(Movie) title:" + arr[0] + ", producer:" + ((Producer) arr[1]).getName()); }
As you see, we have used the createNativeQuery
method to create our native query. We later executed it using getResultList
as we earlier did using JPA queries. But, as you can see, the result set is a list of array objects. That's because the entity manager is...