通过反复试验,我设法弄清楚了如何在我的 Dropwizard 应用程序中使用休眠搜索。事实证明,Dropwizard 不直接支持它,但可以通过少量努力添加。我做了以下事情:
1.在我的pom文件中添加了Hibernate Search依赖:
<!-- Search -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-orm</artifactId>
<version>5.9.0.Final</version>
</dependency>
2.在我的应用程序的run-方法中,我创建了索引器:
// search functionality
try {
EntityManager em = hibernate.getSessionFactory().createEntityManager();
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);
fullTextEntityManager.createIndexer().startAndWait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
3.使用 @Indexed 和 @Field 注释使我的实体类可搜索
@Entity
@Indexed
@Table(name = "product")
public class Product {
@Id
private int id;
@Field(termVector = TermVector.YES)
private String productName;
@Field(termVector = TermVector.YES)
private String description;
@Field
private int memory;
// getters, setters, and constructors
}
4.然后在我的 DAO 类中,我可以按如下方式搜索实体:
public List<Product> search(String term) {
EntityManager em = this.currentSession();
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);
// create native Lucene query unsing the query DSL
// alternatively you can write the Lucene query using the Lucene query parser
// or the Lucene programmatic API. The Hibernate Search DSL is recommended though
QueryBuilder qb = fullTextEntityManager.getSearchFactory()
.buildQueryBuilder()
.forEntity(Product.class)
.get();
org.apache.lucene.search.Query luceneQuery = qb
.keyword()
.onFields("description", "productName")
.matching(term)
.createQuery();
// wrap Lucene query in a javax.persistence.Query
javax.persistence.Query jpaQuery =
fullTextEntityManager.createFullTextQuery(luceneQuery, Product.class);
// execute search
List<Product> result = jpaQuery.getResultList();
return result;
}
我发现this tutorial 在我的实施过程中很有帮助。