Using JPA for queries

Although we will focus on the traditional query API, the downloadable source code also contains a different version of the example application in a chapter3-entitymanager folder. This VAPORware Marketplace variation demonstrates the use of JPA across the board, for both mapping and queries.

In the search controller servlet, rather than using a Hibernate SessionFactory object to create a Session object, it uses a JPA EntityManagerFactory instance to create an EntityManager object:

...
// The "com.packtpub.hibernatesearch.jpa" identifier is declared
// in "META-INF/persistence.xml"
EntityManagerFactory entityManagerFactory =
   Persistence.createEntityManagerFactory(
   "com.packtpub.hibernatesearch.jpa");
EntityManager entityManager =
   entityManagerFactory.createEntityManager();
...

We have already seen code samples that use the traditional query API. In those previous examples, the Hibernate ORM Session objects were wrapped within Hibernate Search FullTextSession objects. These then produced Hibernate SearchFullTextQuery objects, which implement the core org.hibernate.Query interface:

...
FullTextSession fullTextSession = Search.getFullTextSession(session);
...
org.hibernate.search.FullTextQuery hibernateQuery =
   fullTextSession.createFullTextQuery(luceneQuery, App.class);
...

Constrast that with JPA, where regular EntityManager objects are likewise wrapped by FullTextEntityManager objects. These create FullTextQuery objects, implementing the standard javax.persistence.Query interface:

...
FullTextEntityManager fullTextEntityManager =
      org.hibernate.search.jpa.Search.getFullTextEntityManager(
      entityManager);
...
org.hibernate.search.jpa.FullTextQuery jpaQuery =
      fullTextEntityManager.createFullTextQuery(luceneQuery, App.class);
...

The traditional FullTextQuery class and its JPA counterpart are very similar, but they are separate classes imported from different Java packages. Both offer hooks to much of the Hibernate Search functionality that we've seen so far, and will further explore.

Tip

Either version of FullTextQuery can be cast to its respective query type, although doing so costs you direct access to the Hibernate Search methods. So, be sure to call any extension methods prior to casting.

If you need to access the non-standard methods after casting to a JPA query, then you can use that interface's unwrap() method to get back to the underlying FullTextQuery implementation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset