来自任何索引实体的Hibernate搜索搜索

时间:2013-04-22 09:03:52

标签: jpa hibernate-search

我正在使用Hibernate-search在我的Jboss应用程序中搜索数据。我有3个JPA实体类,它们都扩展了BaseEntity类,每个类都被Lucene索引。例如:

@MappedSuperclass
public abstract class BaseEntity implements Serializable {
    @Temporal(TemporalType.TIMESTAMP)
    private Date created;
    public abstract Long getId();
}

@Entity
@Table(name = "DVD")
public class Dvd extends BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Field
    private String title;
}

@Entity
@Table(name = "BOOK")
public class Book extends BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Field
    private String author;
}

现在我想通过通配符搜索查询搜索DVD标题或书籍作者,并将结果列表作为列表。这就是我迄今为止所拥有的:

public List<BaseEntity> search(String query, int firstResult, int maxResults) {
    List<BaseEntity> results = null;
    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);
    Query luceneQuery = new WildcardQuery(new Term("*", "*" + query + "*"));
    FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(luceneQuery, BaseEntity.class);
    fullTextQuery.setFirstResult(firstResult);
    fullTextQuery.setMaxResults(maxResults);
    results = fullTextQuery.getResultList();
    return results;
}

但有了这个,我没有得到任何结果。如何在不使用buildQueryBuilder为每个实体的情况下实现这一点或者是否有可能?谢谢!

1 个答案:

答案 0 :(得分:1)

您需要对类使用varargs样式方法,如下所示:

FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(luceneQuery, DVD.class, Book.class);

这是因为当Hibernate Search创建搜索查询时,它会将类名添加到查询中(对于_hibernate_class字段,这是索引类的名称)。