Question

I'm trying to use JPA with HibernateSearch. I used Example 5.3 in http://docs.jboss.org/hibernate/stable/search/reference/en/html/search-query.html. The results come out as expected.

However, the data coming back is a huge graph. I only need the primary key of the data. So, I tried Example 5.9, but it only shows the Hibernate API. There was not a javax.persistence.Query.setProjection() method.

What can I use to get just the primary key of a search result? Should I try to get the hibernate session from the EntityManager in JPA?

Thanks for any help.

Was it helpful?

Solution

Example 5.3 was a bit misleading. javax.persistence.Query doesn't have to be used. Instead, org.hibernate.search.jpa.FullTextQuery has the setProjection() method that I needed. Here is the resulting code (with fully qualified class names):


        //Open JPA session
        javax.persistence.EntityManagerFactory emf=javax.persistence.Persistence.createEntityManagerFactory("manager1");
        javax.persistence.EntityManager em=emf.createEntityManager();
        em.getTransaction().begin();

        //Make a FullText EM from the JPA session.
        org.hibernate.search.jpa.FullTextEntityManager fullTextSession=org.hibernate.search.jpa.Search.getFullTextEntityManager(em);

        //Build the lucene query.
        org.apache.lucene.queryParser.QueryParser parser=new org.apache.lucene.queryParser.QueryParser("data1",new org.apache.lucene.analysis.standard.StandardAnalyzer());
        org.apache.lucene.search.Query query=parser.parse("FindMe");

        //Convert to a hibernate query.
        org.hibernate.search.jpa.FullTextQuery query2=fullTextSession.createFullTextQuery(query, SampleBean.class);

        //Set the projections
        query2.setProjection("id");

        //Run the query.
        for (Object[] row:(List)query2.getResultList()){
            //Show the list of id's
            System.out.println(row[0]);
        }

        //Close
        em.getTransaction().commit();
        em.close();
        emf.close();

query2 does the projection and all is well!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top