---
title: "hibernate Search类似于Lucene的功能"
author: "hengstart"
date: "2011-02-15T23:29:39Z"
tags: []
categories: ["企业架构"]
slug: "hibernate-search-lucene"
draft: false
lastmod: "2011-02-15T23:29:39Z"
id: 907345
url: "https://hengstart.iteye.com/blog/907345"
---

不久前Hibernate推出了Hibernate Search 3.0 GA，由它的名字大家也可以大概猜到它的作用是对数据库中的数据进行检索的。它是hibernate对著名的全文检索系统Lucene的一个集成方案，作用在于对数据表中某些内容庞大的字段（如声明为text的字段）建立全文索引，这样通过hibernate search就可以对这些字段进行全文检索后获得相应的POJO，从而加快了对内容庞大字段进行模糊搜索的速度（sql语句中like匹配）。

Hibernate Search运行的环境如下：

1、JDK或JRE 5.0以上

2、Hibernate-Search以及相应的依赖包

3、Hibernate Core 3.2.X

4、Hibernate Annotations 3.3.X

一、配置

使用过Lucene的人都知道，Lucene是使用Directory这个概念来存储索引文件的，所以在Hibernate Search中提供了一个初始化、配置化的工厂类DirectoryProvider来生成相应的Directory。而在这里，我使用了FSDirectoryProvider这个工厂类，其中FS代表文件系统，意思是索引文件保存在文件系统中。因此，我们在hibernate.cfg.xml文件中加入了一下内容：

xml 代码

1. &lt;property name="hibernate.search.default.directory\_provider"&gt;
2. org.hibernate.search.store.FSDirectoryProvider
3. &lt;/property&gt;
4. &lt;property name="hibernate.search.default.indexBase"&gt;
5. E:/temp/index
6. &lt;/property&gt;

其中属性hibernate.search.default.indexBase代表索引文件默认的保存位置。

这些属性设置完成后，接下来就是使用Annotation对指定POJO的指定属性进行配置了。如下：

java 代码

01. @Indexed(index = "text")
02. **public** **class** Text **implements** java.io.Serializable
03. {
04. @DocumentId
05. **private** Integer id;
06. **private** String fileName;
07. **private** String filePath;
08. @Field(name = "content", store = Store.NO, index = Index.TOKENIZED, analyzer = @Analyzer(impl = ChineseAnalyzer.**class**))
09. **private** String content;
10. ......
11. }

其中@Indexed用于标示需要建立全文索引的实体类，它包含一个属性index用于标示这个全文索引的名字

@DocumentId用于标示实体类中的唯一的属性保存在索引文件中，是当进行全文检索时可以这个唯一的属性来区分索引中其他实体对象，一般使用实体类中的主键属性

@Field就是用来标示Lucene的Field字段，其中name属性用于标示Field的名称，store属性用于标示这个属性的内容是否需要保存在索引中，index属性标示该字段属性是否进行分词（Index.TOKENIZED），analyzer用于标示建立索引时所使用的分析器是什么类，这里使用Lucene自带的ChineseAnalyzer

 

二、建立索引

配置完成以上设置之后，Hibernate Search的配置工作算是大功告成了，剩下的就是如何在编码时使用到Hibernate Search。其实Hibernate Search的使用与我们平时Hibernate的使用基本一致，索引的建立工作是可以由Hibernate Search后台自动处理的，无需手工操作，其中的主要差别有

1、Configuration

由于本文中Hibernate Search配置是由Annotation来完成的，所以我们在初始化Configuration、SessionFactory、Session时应该这样写：

java 代码

1. factory = **new** AnnotationConfiguration().configure(file).buildSessionFactory();

使用AnnotationConfiguaration来代理平常使用的Configuration

2、Session

要使用Hibernate Search的功能就不能单纯使用平常的Session来开始事务，进行数据库操作，而是应该改用FullTextSession

java 代码

01. //获取Session
02. Session session = HibernateUtil.getSession();
03. //封装Session为FullTextSession
04. FullTextSession fullTextSession = Search.createFullTextSession(session);
05. //开始事务
06. Transaction tx = fullTextSession.beginTransaction();
07. ......
08. //提交事务
09. tx.commit();
10. //关闭会话
11. fullTextSession.close();

这样，我们使用FullTextSession进行save，update，delete操作hibernate search将会自动根据配置在后台对相应的域建立全文索引了

 

三、检索

接下来就是说一下如何使用全文检索功能来检索实体对象了。

java 代码

01. Session session = HibernateUtil.getSession();
02. FullTextSession fullTextSession = Search.createFullTextSession(session);
03. Transaction tx = fullTextSession.beginTransaction();
04. QueryParser parser = **new** QueryParser("content", **new** ChineseAnalyzer());
05. Query query = fullTextSession.createFullTextQuery(parser.parse(word),
06. Text.**class**);
07. List result = query.list();
08. **for** (**int** i = 0; result != **null** && i &lt; result.size(); i++)
09. {
10. Text pojo = (Text) result.get(i);
11. System.out.println("文件名：" + pojo.getFileName());
12. System.out.println("文件路径：" + pojo.getFilePath());
13. System.out.println();
14. }
15. tx.commit();
16. fullTextSession.close();

首先是建立相应的QueryParser由他来对输入的关键字进行切分后产生Lucene下的Query实例，最后通过FullTextSession的createFullTextQuery方法生成hibernate下的Query实例，执行list方法即可获得查询的实例结果集合。

四、完

以上便是今天我对Hibernate Search的一个尝试，属于很基础很基础的入门，希望可以对大家能有一些启发跟帮助，随文附带我的源代码

 

定，下载运行一下，Annotations 以前还没有用过，还是大学生有学习热情啊。