使用Hibernate Search查询Enumerated(枚举)的IndexedEmbedded列表

时间:2015-08-19 11:06:32

标签: java spring hibernate lucene hibernate-search

我有下面的模型,我试图使用Hibernate Search进行全文搜索。

我需要搜索关于"关于"具有UserRole.PROFESSIONIST角色的所有用户的字段。

这是模型:

@Entity
@Indexed
public class User
{
    @Id
    @GeneratedValue
    Long id;

    ...

    String about;

    @IndexedEmbedded
    @Enumerated(EnumType.STRING)
    @ElementCollection(targetClass = UserRole.class, fetch = FetchType.EAGER)
    @JoinTable(name = "user_roles", joinColumns = {@JoinColumn(name = "user_id")})
    List<UserRole> roles = new ArrayList<>();
}    

这是查询:

List results = new ArrayList<>();

org.apache.lucene.search.Query containText = queryBuilder
    .keyword()
    .onField("about")
    .matching(text)
    .createQuery();

org.apache.lucene.search.Query isProfessionist = queryBuilder
    .keyword()
    .onFields("roles")
    .matching(UserRole.PROFESSIONIST.toString())
    .createQuery();

org.apache.lucene.search.Query query = queryBuilder
    .bool()
    .must(containText)
    .must(isProfessionist)
    .createQuery();

org.hibernate.search.jpa.FullTextQuery jpaQuery = fullTextEntityManager.createFullTextQuery(query, User.class);

results = jpaQuery.getResultList();

当我执行查询时,我收到此错误:

org.hibernate.search.exception.SearchException: Unable to find field roles in com.plusimple.core.models.User

我正在尝试做什么?如果是的话,我做错了什么?

1 个答案:

答案 0 :(得分:3)

由于目标类是枚举,因此您必须向要搜索的属性添加@Field注释(嵌入完整实体时不需要这样做,因为它们有自己的子项可搜索的属性。)

示例:

@IndexedEmbedded
@Field(name="roles", analyze=Analyze.NO, index=Index.YES)
@Enumerated(EnumType.STRING)
@ElementCollection(targetClass = UserRole.class, fetch = FetchType.EAGER)
@JoinTable(name = "user_roles", joinColumns = {@JoinColumn(name = "user_id")})
List<UserRole> roles = new ArrayList<>();