[SpringBoot系列]--Spring Hibernate search 注解实现(未测试)

1.maven项目pom.xml加入依赖

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-search-orm</artifactId>

<version>5.5.0.Final</version>

</dependency>

<dependency>

<groupId>org.apache.lucene</groupId>

<artifactId>lucene-queryparser</artifactId>

<version>5.3.0</version>

</dependency>

<!--中文分词器>

<dependency>

<groupId>org.apache.lucene</groupId>

<artifactId>lucene-analyzers-smartcn</artifactId>

<version>5.3.0</version>

</dependency>

2.在application.xml中添加配置

<property name="hibernateProperties">
<props>
//文件系统
<prop key="hibernate.search.default.directory_provider">filesystem</prop>
//索引存储目录
<prop key="hibernate.search.default.indexBase">e:/index</prop>
</props>
</property>

 

3.domain(bean)中实体类配置

 

类上注解

 注释@Indexed将实体类标记为需要通过Hibernate Search进行索引的实体。

 注释@Analyzer(impl=SmartChineseAnalyzer.class),我配置了中文分词器,默认是StandardAnalyzer.calss

类中属性注解

  Hibernate Search需要将实体标识符存储在每个实体的索引中。默认情况下,它将使用标记为@Id的字段,但您可以使用@DocumentId(仅限高级用户)覆盖此字段。

  注释@Field用于实体类属性上,其中参数的默认值为index = Index.YES,analyze = Analyze.YES和store = Store.NO。

  Lucene索引主要是基于字符串的,还有一些额外的数字类型支持。有关更多详情,请参阅Bridges。

关联实体的索引

  @IndexedEmbedded注释用于索引关联实体,如通常通过@ManyToMany,@OneToOne,@ManyToOne,@Embedded和@ElementCollection定义的实体,有关详细信息,请参阅嵌入式和关联对象。

4.注解实体类例子

@Entity
@Table(name = "t_task")
@Indexed
@Analyzer(impl=SmartChineseAnalyzer.class)
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@DocumentId
private Long id;

@Column(name="c_taskname")
@Field
private String taskName;//任务名称
@Column(name="c_address")
private String address;//工作地点
@Column(name = "c_content")
@Field
private String content;// 任务内容

5.全文检索索引初始化

  /*全文搜索索引初始化*/
public void initFullTextIndex() throws Exception{
FullTextSession fullTextSession = Search.getFullTextSession(currentSession());
fullTextSession.createIndexer().startAndWait();
}

6.全文检索查询

/*全文搜索*/
public List fullTextSearch(){
FullTextSession fullTextSession = Search.getFullTextSession(currentSession());
Transaction tx = fullTextSession.beginTransaction();
QueryBuilder qb = fullTextSession.getSearchFactory() .buildQueryBuilder().forEntity(entityType).get();
org.apache.lucene.search.Query query = qb .keyword() .onFields("taskName", "content") .matching("扫黄") .createQuery();
org.hibernate.Query hibQuery =  fullTextSession.createFullTextQuery(query, entityType);
List result = hibQuery.list();
return result;
}

 

原文地址:https://www.cnblogs.com/tanwei81/p/6816532.html