1、开发环境:spring2.5、hibernate3.3.1GA、hibernateSearch3.1.0GA;
2、开发是基于maven上开发的,首先新建一个web工程,添加maven支持,在pom.xml中添加一下几个依赖包:
- <dependencies>
- <dependency>
- <groupId>org.apache.openejb</groupId>
- <artifactId>javaee-api</artifactId>
- <version>5.0-1</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-search</artifactId>
- <version>3.1.0.GA</version>
- </dependency>
- <dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-annotations</artifactId>
- <version>3.4.0.GA</version>
- </dependency>
- <!-- hibernate framework end -->
- <!-- lucene start -->
- <dependency>
- <groupId>org.apache.lucene</groupId>
- <artifactId>lucene-analyzers</artifactId>
- <version>3.0.1</version>
- </dependency>
- <dependency>
- <groupId>org.apache.lucene</groupId>
- <artifactId>lucene-highlighter</artifactId>
- <version>3.0.1</version>
- </dependency>
- </dependencies>
<dependencies> <dependency> <groupId>org.apache.openejb</groupId> <artifactId>javaee-api</artifactId> <version>5.0-1</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-search</artifactId> <version>3.1.0.GA</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId> <version>3.4.0.GA</version> </dependency> <!-- hibernate framework end --> <!-- lucene start --> <dependency> <groupId>org.apache.lucene</groupId> <artifactId>lucene-analyzers</artifactId> <version>3.0.1</version> </dependency> <dependency> <groupId>org.apache.lucene</groupId> <artifactId>lucene-highlighter</artifactId> <version>3.0.1</version> </dependency> </dependencies>
其他就是hibernate+spring的配置了;
注意一点的就是在配置文件hibernate的属性后面加上索引的监听和索引存放的位置,如:
- <!-- Spring管理Hibernate的Mapping对象 -->
- <bean id="sessionFactory"
- class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
- <property name="dataSource">
- <ref bean="dataSource" />
- </property>
- <property name="hibernateProperties">
- <props>
- <prop key="hibernate.dialect">
- ${hibernate.dialect}
- </prop>
- <prop key="hibernate.hbm2ddl.auto">
- ${hibernate.hbm2ddl.auto}
- </prop>
- <prop key="hibernate.show_sql">
- ${hibernate.show_sql}
- </prop>
- <prop key="hibernate.use_sql_comments">
- ${hibernate.use_sql_comments}
- </prop>
- <prop key="hibernate.use_outer_join">
- ${hibernate.use_outer_join}
- </prop>
- <prop key="hibernate.current_session_context_class">
- ${hibernate.current.session.context.class}
- </prop>
- <prop key="connection.autoReconnect">
- ${connection.autoReconnect}
- </prop>
- <prop key="connection.autoReconnectForPools">
- ${connection.autoReconnectForPools}
- </prop>
- <prop key="connection.is-connection-validation-required">
- ${connection.is-connection-validation-required}
- </prop>
- <!-- 索引配置 -->
- <prop key="hibernate.search.default.directory_provider">
- org.hibernate.search.store.FSDirectoryProvider
- </prop>
- <prop key="hibernate.search.default.indexBase">
- d:/JAVA/hibernateIndex
- </prop>
- </props>
- </property>
- <!-- 索引配置-->
- <property name="eventListeners">
- <map>
- <entry key="post-update">
- <bean class="org.hibernate.search.event.FullTextIndexEventListener" />
- </entry>
- <entry key="post-insert">
- <bean class="org.hibernate.search.event.FullTextIndexEventListener" />
- </entry>
- <entry key="post-delete">
- <bean class="org.hibernate.search.event.FullTextIndexEventListener" />
- </entry>
- </map>
- </property>
- <property name="mappingDirectoryLocations">
- <list>
- <value>${hibernate.mappingDirectoryLocations}</value>
- </list>
- </property>
- </bean>
<!-- Spring管理Hibernate的Mapping对象 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> ${hibernate.dialect} </prop> <prop key="hibernate.hbm2ddl.auto"> ${hibernate.hbm2ddl.auto} </prop> <prop key="hibernate.show_sql"> ${hibernate.show_sql} </prop> <prop key="hibernate.use_sql_comments"> ${hibernate.use_sql_comments} </prop> <prop key="hibernate.use_outer_join"> ${hibernate.use_outer_join} </prop> <prop key="hibernate.current_session_context_class"> ${hibernate.current.session.context.class} </prop> <prop key="connection.autoReconnect"> ${connection.autoReconnect} </prop> <prop key="connection.autoReconnectForPools"> ${connection.autoReconnectForPools} </prop> <prop key="connection.is-connection-validation-required"> ${connection.is-connection-validation-required} </prop> <!-- 索引配置 --> <prop key="hibernate.search.default.directory_provider"> org.hibernate.search.store.FSDirectoryProvider </prop> <prop key="hibernate.search.default.indexBase"> d:/JAVA/hibernateIndex </prop> </props> </property> <!-- 索引配置--> <property name="eventListeners"> <map> <entry key="post-update"> <bean class="org.hibernate.search.event.FullTextIndexEventListener" /> </entry> <entry key="post-insert"> <bean class="org.hibernate.search.event.FullTextIndexEventListener" /> </entry> <entry key="post-delete"> <bean class="org.hibernate.search.event.FullTextIndexEventListener" /> </entry> </map> </property> <property name="mappingDirectoryLocations"> <list> <value>${hibernate.mappingDirectoryLocations}</value> </list> </property> </bean>
这时启动如果报slf4j错误,可能是你的slf4j包冲突,需要把你lib里相关的jar包删了,在maven支持中还剩下slf4j-api-1.4.2.jar,需要导入slf4j-logging-1.4.2.jar包,如果导入更高版可能会报错,这个包在百度搜slf4j就能进入它的官网,很容易找到;
这个时候启动如果不报错,那成功一半了;接下来就是配置实体类了,比如一个商城系统要对订单建索引,实体类如(给出关键部分代码):
- @Entity
- @Indexed(index="shopOrders")
- public class ShopOrders implements java.io.Serializable {
- // Fields
- @DocumentId
- private String id;
- private Integer uid;
- @Field(index=Index.TOKENIZED,store=Store.YES)
- private String username;
- @Field(index=Index.UN_TOKENIZED,store=Store.YES)
- private Integer isDelete;
@Entity @Indexed(index="shopOrders") public class ShopOrders implements java.io.Serializable { // Fields @DocumentId private String id; private Integer uid; @Field(index=Index.TOKENIZED,store=Store.YES) private String username; @Field(index=Index.UN_TOKENIZED,store=Store.YES) private Integer isDelete;
这个时候启动你会发现你指定的路径下已经有了一个shopOrders文件夹,如果这个时候去搜索是搜索不到的,还没有初始化数据;
以下是数据初始化和查询的代码:
- import java.util.Date;
- import java.util.List;
- import org.apache.lucene.analysis.standard.StandardAnalyzer;
- import org.apache.lucene.queryParser.MultiFieldQueryParser;
- import org.apache.lucene.queryParser.QueryParser;
- import org.apache.lucene.search.BooleanClause;
- import org.apache.lucene.search.BooleanQuery;
- import org.apache.lucene.search.Query;
- import org.hibernate.CacheMode;
- import org.hibernate.FlushMode;
- import org.hibernate.ScrollMode;
- import org.hibernate.ScrollableResults;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.search.FullTextQuery;
- import org.hibernate.search.FullTextSession;
- import org.hibernate.search.Search;
- import org.springframework.orm.hibernate3.LocalSessionFactoryBean;
- import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
- import com.china.fung.hibernate.pojo.shop.ShopOrders;
- public class Dao extends HibernateDaoSupport {
- private static SessionFactory sessionFactory;
- private static Session session = null;
- private static LocalSessionFactoryBean factoryBean = null;
- public void getMySession() throws Exception {
- sessionFactory = this.getHibernateTemplate().getSessionFactory();
- session = sessionFactory.openSession();
- }
- public List search(String keyword) throws Exception {
- this.getMySession();
- BooleanQuery.setMaxClauseCount(100000);
- BooleanQuery booleanQuery = new BooleanQuery();
- StandardAnalyzer analyzer=new StandardAnalyzer();
- // 基本关键词搜索
- String[] searchFields = new String[] { "username" };//成员变量
- MultiFieldQueryParser queryParser = new MultiFieldQueryParser(
- searchFields,analyzer);
- queryParser.setDefaultOperator(QueryParser.Operator.AND);
- Query query = queryParser.parse(keyword);
- booleanQuery.add(query,BooleanClause.Occur.MUST);
- QueryParser parse=new QueryParser("isDelete",analyzer);
- Query query1=parse.parse("0");
- parse.setDefaultOperator(QueryParser.Operator.AND);
- booleanQuery.add(query1,BooleanClause.Occur.MUST);
- FullTextSession fullSession = Search.getFullTextSession(session);
- FullTextQuery fullQuery = fullSession.createFullTextQuery(booleanQuery,
- ShopOrders.class);
- int size = fullQuery.getResultSize();
- System.out.println("size:" + size);
- return fullQuery.list();
- }
- public void createIndexByHibernateSearch() throws Exception{
- this.getMySession();
- long startTime = new Date().getTime();
- int BATCH_SIZE = 1000;
- FullTextSession s = Search.getFullTextSession(session);
- // Transaction tr = s.beginTransaction();
- s.setFlushMode(FlushMode.MANUAL);
- s.setCacheMode(CacheMode.IGNORE);
- ScrollableResults results = s.createQuery("from ShopOrders").setFetchSize(BATCH_SIZE).scroll(ScrollMode.FORWARD_ONLY);
- int index = 0;
- while (results.next()) {
- index++;
- s.index(results.get(0)); // index each element
- if (index % BATCH_SIZE == 0) {
- // s.flushToIndexes(); //apply changes to indexes
- s.clear(); // clear since the queue is processed
- }
- }
- s.clear();
- long endTime = new Date().getTime();
- logger.warn("建立Product索引 , 这花费了" + (endTime - startTime) + " 毫秒来把文档增加到索引里面去!");
- // tr.commit();
- }
- }
import java.util.Date; import java.util.List; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.queryParser.MultiFieldQueryParser; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.Query; import org.hibernate.CacheMode; import org.hibernate.FlushMode; import org.hibernate.ScrollMode; import org.hibernate.ScrollableResults; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.search.FullTextQuery; import org.hibernate.search.FullTextSession; import org.hibernate.search.Search; import org.springframework.orm.hibernate3.LocalSessionFactoryBean; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.china.fung.hibernate.pojo.shop.ShopOrders; public class Dao extends HibernateDaoSupport { private static SessionFactory sessionFactory; private static Session session = null; private static LocalSessionFactoryBean factoryBean = null; public void getMySession() throws Exception { sessionFactory = this.getHibernateTemplate().getSessionFactory(); session = sessionFactory.openSession(); } public List search(String keyword) throws Exception { this.getMySession(); BooleanQuery.setMaxClauseCount(100000); BooleanQuery booleanQuery = new BooleanQuery(); StandardAnalyzer analyzer=new StandardAnalyzer(); // 基本关键词搜索 String[] searchFields = new String[] { "username" };//成员变量 MultiFieldQueryParser queryParser = new MultiFieldQueryParser( searchFields,analyzer); queryParser.setDefaultOperator(QueryParser.Operator.AND); Query query = queryParser.parse(keyword); booleanQuery.add(query,BooleanClause.Occur.MUST); QueryParser parse=new QueryParser("isDelete",analyzer); Query query1=parse.parse("0"); parse.setDefaultOperator(QueryParser.Operator.AND); booleanQuery.add(query1,BooleanClause.Occur.MUST); FullTextSession fullSession = Search.getFullTextSession(session); FullTextQuery fullQuery = fullSession.createFullTextQuery(booleanQuery, ShopOrders.class); int size = fullQuery.getResultSize(); System.out.println("size:" + size); return fullQuery.list(); } public void createIndexByHibernateSearch() throws Exception{ this.getMySession(); long startTime = new Date().getTime(); int BATCH_SIZE = 1000; FullTextSession s = Search.getFullTextSession(session); // Transaction tr = s.beginTransaction(); s.setFlushMode(FlushMode.MANUAL); s.setCacheMode(CacheMode.IGNORE); ScrollableResults results = s.createQuery("from ShopOrders").setFetchSize(BATCH_SIZE).scroll(ScrollMode.FORWARD_ONLY); int index = 0; while (results.next()) { index++; s.index(results.get(0)); // index each element if (index % BATCH_SIZE == 0) { // s.flushToIndexes(); //apply changes to indexes s.clear(); // clear since the queue is processed } } s.clear(); long endTime = new Date().getTime(); logger.warn("建立Product索引 , 这花费了" + (endTime - startTime) + " 毫秒来把文档增加到索引里面去!"); // tr.commit(); } }
好了,到这基本就完事了,只需要在service里调用就行了,别忘了,先调用createIndexByHibernateSearch方法初始化(一次就行),再调用search方法搜索;
相关推荐
**Hibernate Search配置及简单应用** Hibernate Search是Hibernate框架的一个扩展,它允许我们在应用程序中实现全文检索功能,使得数据库中的数据可以被快速、高效地搜索。这个功能尤其在处理大量文本数据时非常...
使用hibernate search实现全文检索和文档管理功能: 1 全文检索 2 手动生成索引 3 文档上传(自动建立索引) 4 文档更新(自动建立索引) 5 文档删除 使用说明: 1 需要先恢复数据库 searchDB_2008sqlserver.bak 2 ...
本例子将深入探讨如何使用Hibernate Search来实现这一功能。 ### 1. 全文检索 全文检索允许用户通过输入关键词来搜索相关的数据,而不仅仅局限于精确匹配。Hibernate Search通过集成Apache Lucene库实现了这个功能...
hibernate-search小例子,myeclipse工程文件,有jar包,只要有mysql和myeclipse就可以直接运行。文章在http://blog.csdn.net/hortond。对文件索引和数据库感兴趣的可以下来看看,lucene是个很强大的全文搜索引擎。
hibernate search的例子,使用的spring.version:3.2.1.RELEASE hibernate.version:4.2.0.Final hibernate-search.version:4.2.0.Final
**hibernateSearch 搜索 索引列子源代码** Hibernate Search 是 Hibernate 的一个扩展模块,它将全文搜索引擎的功能集成到了 Java 应用中,允许开发者在数据库中进行复杂的文本搜索。本教程将深入探讨 Hibernate ...
- **启用 Hibernate Search**:可以通过 `<property name="hibernate.search.default.directory_provider" value="ram"/>` 来指定默认的索引存储方式。 - **指定索引位置**:例如 `<property name="hibernate.search...
Hibernate是一款开源的对象关系映射(Object/Relational Mapping,ORM)框架,它用于Java语言,并且与Hibernate Search、Hibernate Validator等组件一起为Java EE和Java SE应用程序提供持久化服务。Hibernate不仅...
这些依赖包括了Hibernate Search模块以及Lucene库,Lucene是Hibernate Search背后的全文搜索引擎。 接下来,我们需要配置Hibernate以启用搜索功能。在应用的配置文件中,例如hibernate.cfg.xml,你需要指定搜索索引...
dwz官方例子 开发环境: 1) 数据库:mysql 请修改 src/hibernate_mysql.cfg.xml这个文件的数据库连接 创建数据库dwz4j 导入测试数据:db/dwz4j.sql mysql -u root -p dwz4j 2) JDK 1.6 3) 项目文件UTF-8编码,如果...
5. **查找用户**:用户发起`search.do`请求,跳转到`search.jsp`展示搜索结果。 在实现这些功能时,通常会设计一个后台业务层(Service),如`StudentManager`类,处理Action的业务逻辑,同时Action与Service之间...
mvn-search用于搜索Maven Central的命令行工具 对于那些喜欢在命令行中搜索Maven依赖关系而不是search.maven.org的Web UI的开发人员而言,这是一个实用程序... mvn-search hibernate-validator mvn-search g:org.slf4j
"使用方法在给的rar中有个例子"意味着在提供的RAR压缩文件中,包含了如何使用Storm-Search的示例项目或教程。RAR是一种常见的文件压缩格式,用户可以通过解压找到包含的文档和代码示例,以学习如何将Storm-Search...
虽然它没有实现分页,但对于初学者来说,理解这个例子可以帮助他们更好地掌握JSF的UI设计、Managed Bean的使用以及通过Hibernate进行数据库操作的基本流程。对于进一步的学习,开发者可以尝试添加更多复杂的功能,如...
包括与本申请是一个例子DBModule (玛利亚/ MySQL数据库)和SearchModule (ElasticSearch)。 提供的示例说明了使用可用的一些功能和,并演示了如何在Dropwizard中使用这些功能。 数据库示例由以下类组成: ...
- "Hibernate_search.ppt" 和 "lucene.ppt" 可能是相关的演示文稿,它们可能详细解释了如何配置和使用Hibernate Search,以及Lucene的原理和实践。 通过学习和实践这些文档,开发者不仅可以掌握Lucene的基本用法,...
1.2. 第一个例子:注册示例.............................................................................................................................................. 15 1.2.1. 了解代码.................
在给定的例子中,`RakeOffAdvice`实现了`AfterReturningAdvice`接口,当`BookBizImpl`的`buy`方法执行完毕并返回值后,`afterReturning`方法会被调用,从而实现销售返利的记录功能。配置文件中的切入点表达式需要...
1个目标文件,JNDI的使用例子,有源代码,可以下载参考,JNDI的使用,初始化Context,它是连接JNDI树的起始点,查找你要的对象,打印找到的对象,关闭Context…… ftp文件传输 2个目标文件,FTP的目标是:(1)提高...