hibernate search 例子

1、开发环境:spring2.5、hibernate3.3.1GA、hibernateSearch3.1.0GA;

2、开发是基于maven上开发的,首先新建一个web工程,添加maven支持,在pom.xml中添加一下几个依赖包:

Java代码 复制代码  收藏代码
  1.  <dependencies>      
  2.   <dependency>  
  3.       <groupId>org.apache.openejb</groupId>  
  4.       <artifactId>javaee-api</artifactId>  
  5.       <version>5.0-1</version>  
  6.       <scope>provided</scope>  
  7.     </dependency>  
  8.         <dependency>    
  9.     <groupId>org.hibernate</groupId>    
  10.     <artifactId>hibernate-search</artifactId>    
  11.     <version>3.1.0.GA</version>    
  12.     </dependency>    
  13.     <dependency>    
  14.         <groupId>org.hibernate</groupId>    
  15.         <artifactId>hibernate-annotations</artifactId>    
  16.         <version>3.4.0.GA</version>    
  17.     </dependency>      
  18.       
  19. <!-- hibernate framework end -->    
  20.        
  21. <!-- lucene start -->    
  22. <dependency>    
  23.     <groupId>org.apache.lucene</groupId>    
  24.     <artifactId>lucene-analyzers</artifactId>    
  25.     <version>3.0.1</version>    
  26. </dependency>    
  27. <dependency>    
  28.     <groupId>org.apache.lucene</groupId>    
  29.     <artifactId>lucene-highlighter</artifactId>    
  30.     <version>3.0.1</version>    
  31. </dependency>    
  32.   </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的属性后面加上索引的监听和索引存放的位置,如:

Java代码 复制代码  收藏代码
  1. <!-- Spring管理Hibernate的Mapping对象 -->  
  2.     <bean id="sessionFactory"  
  3.         class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
  4.         <property name="dataSource">  
  5.             <ref bean="dataSource" />  
  6.         </property>  
  7.         <property name="hibernateProperties">  
  8.             <props>  
  9.                 <prop key="hibernate.dialect">  
  10.                     ${hibernate.dialect}  
  11.                 </prop>  
  12.                 <prop key="hibernate.hbm2ddl.auto">  
  13.                     ${hibernate.hbm2ddl.auto}  
  14.                 </prop>  
  15.                 <prop key="hibernate.show_sql">  
  16.                     ${hibernate.show_sql}  
  17.                 </prop>  
  18.                 <prop key="hibernate.use_sql_comments">  
  19.                     ${hibernate.use_sql_comments}  
  20.                 </prop>  
  21.                 <prop key="hibernate.use_outer_join">  
  22.                     ${hibernate.use_outer_join}  
  23.                 </prop>  
  24.                 <prop key="hibernate.current_session_context_class">  
  25.                     ${hibernate.current.session.context.class}  
  26.                 </prop>  
  27.                 <prop key="connection.autoReconnect">  
  28.                     ${connection.autoReconnect}  
  29.                 </prop>   
  30.                 <prop key="connection.autoReconnectForPools">  
  31.                     ${connection.autoReconnectForPools}  
  32.                 </prop>   
  33.                 <prop key="connection.is-connection-validation-required">  
  34.                     ${connection.is-connection-validation-required}  
  35.                 </prop>   
  36.                   
  37.                 <!-- 索引配置 -->  
  38.                 <prop key="hibernate.search.default.directory_provider">  
  39.                     org.hibernate.search.store.FSDirectoryProvider  
  40.                 </prop>  
  41.                 <prop key="hibernate.search.default.indexBase">  
  42.                     d:/JAVA/hibernateIndex  
  43.                 </prop>  
  44.                    
  45.             </props>  
  46.         </property>  
  47.           
  48.         <!-- 索引配置-->  
  49.         <property name="eventListeners">    
  50.             <map>    
  51.                 <entry key="post-update">    
  52.                     <bean class="org.hibernate.search.event.FullTextIndexEventListener" />    
  53.                 </entry>    
  54.                 <entry key="post-insert">    
  55.                     <bean class="org.hibernate.search.event.FullTextIndexEventListener" />    
  56.                 </entry>    
  57.                 <entry key="post-delete">    
  58.                     <bean class="org.hibernate.search.event.FullTextIndexEventListener" />    
  59.                 </entry>    
  60.             </map>    
  61.         </property>  
  62.           
  63.         <property name="mappingDirectoryLocations">  
  64.             <list>  
  65.                 <value>${hibernate.mappingDirectoryLocations}</value>  
  66.             </list>  
  67.         </property>  
  68.     </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就能进入它的官网,很容易找到;

这个时候启动如果不报错,那成功一半了;接下来就是配置实体类了,比如一个商城系统要对订单建索引,实体类如(给出关键部分代码):

Java代码 复制代码  收藏代码
  1. @Entity  
  2. @Indexed(index="shopOrders")  
  3. public class ShopOrders  implements java.io.Serializable {  
  4.   
  5.   
  6.     // Fields      
  7.   
  8.      @DocumentId  
  9.      private String id;  
  10.      private Integer uid;  
  11.      @Field(index=Index.TOKENIZED,store=Store.YES)  
  12.      private String username;  
  13.      @Field(index=Index.UN_TOKENIZED,store=Store.YES)  
  14.      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文件夹,如果这个时候去搜索是搜索不到的,还没有初始化数据;
以下是数据初始化和查询的代码:

Java代码 复制代码  收藏代码
  1. import java.util.Date;  
  2. import java.util.List;  
  3.   
  4. import org.apache.lucene.analysis.standard.StandardAnalyzer;  
  5. import org.apache.lucene.queryParser.MultiFieldQueryParser;  
  6. import org.apache.lucene.queryParser.QueryParser;  
  7. import org.apache.lucene.search.BooleanClause;  
  8. import org.apache.lucene.search.BooleanQuery;  
  9. import org.apache.lucene.search.Query;  
  10. import org.hibernate.CacheMode;  
  11. import org.hibernate.FlushMode;  
  12. import org.hibernate.ScrollMode;  
  13. import org.hibernate.ScrollableResults;  
  14. import org.hibernate.Session;  
  15. import org.hibernate.SessionFactory;  
  16. import org.hibernate.search.FullTextQuery;  
  17. import org.hibernate.search.FullTextSession;  
  18. import org.hibernate.search.Search;  
  19. import org.springframework.orm.hibernate3.LocalSessionFactoryBean;  
  20. import org.springframework.orm.hibernate3.support.HibernateDaoSupport;  
  21.   
  22. import com.china.fung.hibernate.pojo.shop.ShopOrders;  
  23.   
  24. public class Dao extends HibernateDaoSupport {  
  25.   
  26.     private static SessionFactory sessionFactory;  
  27.     private static Session session = null;  
  28.     private static LocalSessionFactoryBean factoryBean = null;  
  29.   
  30.     public void getMySession() throws Exception {  
  31.         sessionFactory = this.getHibernateTemplate().getSessionFactory();  
  32.         session = sessionFactory.openSession();  
  33.     }  
  34.   
  35.     public List search(String keyword) throws Exception {  
  36.         this.getMySession();  
  37.         BooleanQuery.setMaxClauseCount(100000);  
  38.         BooleanQuery booleanQuery = new BooleanQuery();  
  39.         StandardAnalyzer analyzer=new StandardAnalyzer();  
  40.         // 基本关键词搜索  
  41.         String[] searchFields = new String[] { "username" };//成员变量  
  42.         MultiFieldQueryParser queryParser = new MultiFieldQueryParser(  
  43.                 searchFields,analyzer);  
  44.         queryParser.setDefaultOperator(QueryParser.Operator.AND);  
  45.         Query query = queryParser.parse(keyword);  
  46.         booleanQuery.add(query,BooleanClause.Occur.MUST);  
  47.           
  48.         QueryParser parse=new QueryParser("isDelete",analyzer);  
  49.         Query query1=parse.parse("0");  
  50.         parse.setDefaultOperator(QueryParser.Operator.AND);  
  51.         booleanQuery.add(query1,BooleanClause.Occur.MUST);  
  52.   
  53.         FullTextSession fullSession = Search.getFullTextSession(session);  
  54.         FullTextQuery fullQuery = fullSession.createFullTextQuery(booleanQuery,  
  55.                 ShopOrders.class);  
  56.         int size = fullQuery.getResultSize();  
  57.         System.out.println("size:" + size);  
  58.           
  59.         return fullQuery.list();  
  60.     }  
  61.       
  62.      public void createIndexByHibernateSearch() throws Exception{  
  63.          this.getMySession();  
  64.           long startTime = new Date().getTime();  
  65.           int BATCH_SIZE = 1000;  
  66.           FullTextSession s = Search.getFullTextSession(session);  
  67.   
  68.           // Transaction tr = s.beginTransaction();  
  69.           s.setFlushMode(FlushMode.MANUAL);  
  70.           s.setCacheMode(CacheMode.IGNORE);  
  71.           ScrollableResults results = s.createQuery("from ShopOrders").setFetchSize(BATCH_SIZE).scroll(ScrollMode.FORWARD_ONLY);  
  72.           int index = 0;  
  73.           while (results.next()) {  
  74.            index++;  
  75.            s.index(results.get(0)); // index each element  
  76.            if (index % BATCH_SIZE == 0) {  
  77.             // s.flushToIndexes(); //apply changes to indexes  
  78.             s.clear(); // clear since the queue is processed  
  79.            }  
  80.           }  
  81.           s.clear();  
  82.           long endTime = new Date().getTime();  
  83.           logger.warn("建立Product索引 , 这花费了" + (endTime - startTime) + " 毫秒来把文档增加到索引里面去!");  
  84.           // tr.commit();  
  85.   
  86.          }  
  87.       
  88.   
  89. }  
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)