public class Product {
private Long id;
private String name;
private String description;
}
有没有办法使用JpaRepository实现对Product类的描述进行全文搜索?
public class Product {
private Long id;
private String name;
private String description;
}
基本上,您将拥有如下代码片段。请记住,在此之前需要重新索引数据库!有关更多信息,请参见入门指南。
使用 Hibernate Search 6+:
@Indexed // Add this
public class Product {
private Long id;
@FullTextField // And this
private String name;
@FullTextField // And this
private String description;
}
public interface ProductRepository extends CrudRepository<Product, Long>, CustomizedProductRepository {
// Declare automatically generated methods here
}
public interface CustomizedProductRepository {
List<Product> search(String terms, int limit, int offset);
}
public class CustomizedProductRepositoryImpl implements CustomizedProductRepository {
@PersistenceContext
private EntityManager em;
@Override
public List<Product> search(String terms, int limit, int offset) {
return Search.session(em).search(Product.class)
.where(f -> f.match()
.fields("name", "description")
.matching(terms))
.fetchHits(offset, limit);
}
}
使用Hibernate Search 5进行OR操作:
@Indexed // Add this
public class Product {
private Long id;
@Field // And this
private String name;
@Field // And this
private String description;
}
public interface ProductRepository extends CrudRepository<Product, Long>, CustomizedProductRepository {
// Declare automatically generated methods here
}
public interface CustomizedProductRepository {
List<Product> search(String terms, int limit, int offset);
}
public class CustomizedProductRepositoryImpl implements CustomizedProductRepository {
@PersistenceContext
private EntityManager em;
@Override
public List<Product> search(String terms, int limit, int offset) {
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);
QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory()
.buildQueryBuilder().forEntity(Product.class).get();
org.apache.lucene.search.Query luceneQuery = queryBuilder
.keyword()
.onFields("name", "description")
.matching(terms)
.createQuery();
// wrap Lucene query in a javax.persistence.Query
javax.persistence.Query jpaQuery =
fullTextEntityManager.createFullTextQuery(luceneQuery, Product.class);
jpaQuery.setMaxResults(limit);
jpaQuery.setFirstResult(offset);
// execute search
return jpaQuery.getResultList();
}
}