hibernate-search-5.1.1简易使用

系统要求java7和hibernate-core-4.3.8,此外还依赖如下jar包

技术分享

使用demo如下:

package com.ciaos.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Transaction;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ciaos.dao.Account;
import com.ciaos.dao.HibernateSessionFactory;

@Controller
public class SearchController {
    
    //索引
    @RequestMapping(value="/index", method={RequestMethod.GET}) 
    public void index(HttpServletRequest req, HttpServletResponse resp){
         try {
             FullTextSession fullTextSession = Search.getFullTextSession(HibernateSessionFactory.getSession());
             try {
                fullTextSession.createIndexer().startAndWait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
             
            PrintWriter out = resp.getWriter();
            out.print("Done");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    //搜索
    @RequestMapping(value="/search", method={RequestMethod.POST,RequestMethod.GET}) 
    public void search(HttpServletRequest req, HttpServletResponse resp){
         try {
            String keyword = req.getParameter("keyword");
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("text/html; charset=utf-8");
            PrintWriter out = resp.getWriter();
            
            FullTextSession fullTextSession = Search.getFullTextSession(HibernateSessionFactory.getSession());
            Transaction tx = fullTextSession.beginTransaction();

            // create native Lucene query using the query DSL
            // alternatively you can write the Lucene query using the Lucene query parser
            // or the Lucene programmatic API. The Hibernate Search DSL is recommended though
            QueryBuilder qb = fullTextSession.getSearchFactory()
              .buildQueryBuilder().forEntity(Account.class).get();
            org.apache.lucene.search.Query query = qb
              .keyword()
              .onFields("name")
              .matching(keyword)
              .createQuery();

            // wrap Lucene query in a org.hibernate.Query
            org.hibernate.Query hibQuery =
                fullTextSession.createFullTextQuery(query, Account.class);

            // execute search
            List result = hibQuery.list();

            tx.commit();
            
            System.out.println(keyword);
            for(int i = 0;i < result.size();i++){
                Account account = (Account) result.get(i);
                out.print("Result " + keyword + " " + account.getName());
            }
            out.print("Search Done");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

POJO文件增加Field注解如下

package com.ciaos.dao;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;

import static javax.persistence.GenerationType.IDENTITY;

import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.Store;

/**
 * Account entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "account", catalog = "test")
@Indexed(index="account")
public class Account implements java.io.Serializable {

    // Fields

    private Integer id;
    
    private String name;

    // Constructors

    /** default constructor */
    public Account() {
    }

    /** full constructor */
    public Account(String name) {
        this.name = name;
    }

    // Property accessors
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Column(name = "name")
    @Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

配置文件

applicationContext.xml(hibernate4放弃CacheProvider,所以不能用org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean)

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">


    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="configLocation"
            value="classpath:hibernate.cfg.xml">
        </property>
    </bean>
</beans>

hibernate.cfg.xml,property增加如下配置

<property name="hibernate.search.default.directory_provider">org.hibernate.search.store.impl.FSDirectoryProvider</property>  
<property name="hibernate.search.default.indexBase">e:\test</property>

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。