1.5. 検索

次に最初の検索を実行します。一般的な方法は、ネイティブの Lucene クエリを作成し、Hibernate API から使い慣れているすべての機能を取得するためにこのクエリを org.hibernate.Query にラップします。以下のコードはインデックス化されたフィールドに対してクエリを準備して実行し、 Book のリストを返します。

例1.8 Hibernate Session を使用して検索を作成および実行

FullTextSession fullTextSession = Search.getFullTextSession(session);
Transaction tx = fullTextSession.beginTransaction();

// create native Lucene query
String[] fields = new String[]{"title", "subtitle", "authors.name", "publicationDate"};
MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, new StandardAnalyzer());
org.apache.lucene.search.Query query = parser.parse( "Java rocks!" );

// wrap Lucene query in a org.hibernate.Query
org.hibernate.Query hibQuery = fullTextSession.createFullTextQuery(query, Book.class);

// execute search
List result = hibQuery.list();
  
tx.commit();
session.close();

例1.9 JPA を使用して検索を作成および実行

EntityManager em = entityManagerFactory.createEntityManager();
FullTextEntityManager fullTextEntityManager = 
    org.hibernate.search.jpa.Search.getFullTextEntityManager(em);
em.getTransaction().begin();

// create native Lucene query
String[] fields = new String[]{"title", "subtitle", "authors.name", "publicationDate"};
MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, new StandardAnalyzer());
org.apache.lucene.search.Query query = parser.parse( "Java rocks!" );

// wrap Lucene query in a javax.persistence.Query
javax.persistence.Query persistenceQuery = fullTextEntityManager.createFullTextQuery(query, Book.class);

// execute search
List result = persistenceQuery.getResultList();

em.getTransaction().commit();
em.close();