如何使用QueryBuilder,Lucene Query& amp;显示hibernate搜索结果FullTextQuery?

时间:2016-07-19 06:08:02

标签: java mysql hibernate lucene hibernate-search

如何仅使用带有订单子句的FullTextEntity Manager显示结果。

  EntityManager em = factory.createEntityManager();
  FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);
  QueryBuilder qb = fullTextEntityManager.getSearchFactory()
                        .buildQueryBuilder().forEntity( Desh.class ).get();

  org.apache.lucene.search.Query query = new org.apache.lucene.search.MatchAllDocsQuery();
  //Also used qb.all().getQuery(); but no results

  FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(query, Desh.class);
  System.out.println(""+ query);
  System.out.println(""+ query.toString());

  fullTextQuery.setSort(new Sort(new SortField("DeshName_for_sort", SortField.STRING, true)));
  //Also used DESH but no results

  fullTextQuery.setFirstResult(0).setMaxResults(60);
  System.out.println("" + fullTextQuery);  
  System.out.println("" + fullTextQuery.getParameters());

  int size = fullTextQuery.getResultSize();
  List<Desh> result = fullTextQuery.getResultList();
  System.out.println("Size e -> "+ size);
  System.out.println("Size e -> "+ result.size());
  for (Deshuser : result) {
    System.out.println("Id: " + user.getId());
    System.out.println("Person Id:" + user.getName());
  }

Desh - 实体类:

@Entity
@Table(name = "DESH")
@XmlRootElement
@Indexed

public class Desh implements Serializable {
 private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "ID")
private Long id;

@Fields({ @Field(index = Index.YES, store = Store.NO), @Field(name = "DeshName_for_sort", index = Index.YES, analyze = Analyze.NO) })
@Column(name = "NAME", length = 100)
private String name;

public Desh () {
}

public Desh (Long id) {
    this.id = id;
}

public Desh (Long id) {
    this.id = id;

}

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}



public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}


@Override
public String toString() {
    return "in.hibprac.hibernatepractice.Desh[ id=" + id + " ]";
}

}

当我在程序上面运行时,它返回没有大小。但是当我使用Namedquery和Native Query返回时,它执行得很好。即使我在代码中删除排序语句,它也不返回任何内容。任何人都可以指导我问题在哪里?

1 个答案:

答案 0 :(得分:1)

试试这个:

FullTextEntityManager ftem=Search.getFullTextEntityManager(entityManager);
ftem.createIndexer().startAndWait();

启动索引,定位所有使用@Indexed

注释的实体