我正在使用Spring Boot和Spring Data Jpa(Hibernate)开发Web应用程序。由于需要全文搜索功能,我集成了Hibernate搜索引擎,但除非我通过
进行手动索引,否则不会对Enities编制索引fullTextEntityManager.createIndexer()startAndWait();
如果我对所有实体进行手动索引,那么一切正常,但如果我使用save() - CrudRepository的方法,则不会创建索引。
public interface JobRepositoryCustom {
public List<Job> searchJobs(SearchDto searchDto);
}
public class JobRepositoryImpl implements JobRepositoryCustom {
@PersistenceContext
private EntityManager entityManager;
@Override
public List<Job> searchJobs(SearchDto searchDto) {
List<Job> jobs;
FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search.getFullTextEntityManager(entityManager);
/*
try {
fullTextEntityManager.createIndexer().startAndWait();
} catch (InterruptedException e) {
System.out.println("An error occurred trying to build the serach index: " + e.toString());
}*/
QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Job.class).get();
org.apache.lucene.search.Query luceneQuery = queryBuilder.bool().must(queryBuilder.keyword().onFields("title", "introduction").matching(searchDto.getSearchTerm()).createQuery()).createQuery();
org.hibernate.search.jpa.FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(luceneQuery, Job.class);
jobs = fullTextQuery.getResultList();
return jobs;
}
}
@Repository
public interface JobRepository extends CrudRepository<Job, Integer>, JobRepositoryCustom {
}