Dropwizard 休眠搜索

Dropwizard Hibernate Search

我正忙于 Dropwizard 应用程序,想在我的数据库中搜索某些实体。我已经看到这可以通过在 Entity 类 的顶部创建 NamedQuery 语句来完成,就像在 this tutorial 中一样。然后从 DAO 类.

执行查询

我偶然发现了 Hibernate search and it seems to be a better solution when it comes to searching for entities in the database. Therefore my question is if it is supported by the Dropwizard framework? Furthermore, if it is supported how would one configure and use it? I failed to find any reference to it in Dropwizard's hibernate documentation

我通过反复试验弄清楚了如何在我的 Dropwizard 应用程序中使用休眠搜索。事实证明 Dropwizard 不直接支持它,但可以通过少量努力添加。我做了以下事情:

1.Added 我的 pom 文件中的 Hibernate 搜索依赖项:

    <!-- Search -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-search-orm</artifactId>
        <version>5.9.0.Final</version>
    </dependency>

2.In 我的应用程序的 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.Made 我的实体 类 可使用 @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.Then 在我的 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 在实施过程中很有帮助。