关于Hibernate Search转载文章

1、创建POJO
package  com.yehui;

import  javax.persistence.CascadeType;
import  javax.persistence.Column;
import  javax.persistence.Entity;
import  javax.persistence.GeneratedValue;
import  javax.persistence.GenerationType;
import  javax.persistence.Id;
import  javax.persistence.JoinColumn;
import  javax.persistence.ManyToOne;
import  javax.persistence.Table;

import  org.hibernate.search.annotations.DocumentId;
import  org.hibernate.search.annotations.Field;
import  org.hibernate.search.annotations.Index;
import  org.hibernate.search.annotations.Indexed;
import  org.hibernate.search.annotations.IndexedEmbedded;
import  org.hibernate.search.annotations.Store;

/**
 * Employee generated by MyEclipse Persistence Tools
 
*/

@Entity
@Table(name 
=   " employee " , catalog  =   " hise " , uniqueConstraints  =   {} )
@Indexed(index 
=   " indexes/employee " )
public   class  Employee  implements  java.io.Serializable  {
    
private static final long serialVersionUID = 7794235365739814541L;
    
private Integer empId;
    
private String empName;
    
private Department dept;
    
private String empNo;
    
private Double empSalary;

    
// Constructors

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


    
/** minimal constructor */
    
public Employee(Integer empId){
        
this.empId = empId;
    }


    
/** full constructor */
    
public Employee(Integer empId, String empName,
            String empNo, Double empSalary)
{
        
this.empId = empId;
        
this.empName = empName;
        
this.empNo = empNo;
        
this.empSalary = empSalary;
    }


    
// Property accessors
    @Id
    @GeneratedValue(strategy 
= GenerationType.AUTO)
    @Column(name 
= "emp_id", unique = true, nullable = false, insertable = true, updatable = true)
    @DocumentId
    
public Integer getEmpId() {
        
return this.empId;
    }


    
public void setEmpId(Integer empId) {
        
this.empId = empId;
    }


    @Column(name 
= "emp_name", unique = false, nullable = true, insertable = true, updatable = true, length = 30)
    @Field(name
="name", index=Index.TOKENIZED, store=Store.YES)
    
public String getEmpName() {
        
return this.empName;
    }


    
public void setEmpName(String empName) {
        
this.empName = empName;
    }


    @Column(name 
= "emp_no", unique = false, nullable = true, insertable = true, updatable = true, length = 30)
    @Field(index
=Index.UN_TOKENIZED)
    
public String getEmpNo() {
        
return this.empNo;
    }


    
public void setEmpNo(String empNo) {
        
this.empNo = empNo;
    }


    @Column(name 
= "emp_salary", unique = false, nullable = true, insertable = true, updatable = true, precision = 7)
    
public Double getEmpSalary(){
        
return this.empSalary;
    }


    
public void setEmpSalary(Double empSalary) {
        
this.empSalary = empSalary;
    }


    @ManyToOne(cascade 
= CascadeType.ALL)
    @JoinColumn(name
="dept_id")
    @IndexedEmbedded(prefix
="dept_", depth=1)
    
public Department getDept() {
        
return dept;
    }


    
public void setDept(Department dept) {
        
this.dept = dept;
    }


}

package  com.yehui;

import  java.util.List;

import  javax.persistence.Column;
import  javax.persistence.Entity;
import  javax.persistence.GeneratedValue;
import  javax.persistence.GenerationType;
import  javax.persistence.Id;
import  javax.persistence.OneToMany;
import  javax.persistence.Table;

import  org.hibernate.search.annotations.ContainedIn;
import  org.hibernate.search.annotations.DocumentId;
import  org.hibernate.search.annotations.Field;
import  org.hibernate.search.annotations.Index;
import  org.hibernate.search.annotations.Indexed;
import  org.hibernate.search.annotations.Store;

/**
 * Department generated by MyEclipse Persistence Tools
 
*/

@Entity
@Table(name 
=   " department " , catalog  =   " hise " , uniqueConstraints  =   {} )
@Indexed(index
= " indexes/department " )
public   class  Department  implements  java.io.Serializable  {
    
private static final long serialVersionUID = 7891065193118612907L;
    
private Integer deptId;
    
private String deptNo;
    
private String deptName;
    
private List<Employee> empList;

    
// Constructors

    @OneToMany(mappedBy
="dept")
    @ContainedIn
    
public List<Employee> getEmpList() {
        
return empList;
    }


    
public void setEmpList(List<Employee> empList) {
        
this.empList = empList;
    }


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


    
/** minimal constructor */
    
public Department(Integer deptId) {
        
this.deptId = deptId;
    }


    
/** full constructor */
    
public Department(Integer deptId, String deptNo, String deptName) {
        
this.deptId = deptId;
        
this.deptNo = deptNo;
        
this.deptName = deptName;
    }


    
// Property accessors
    @Id
    @GeneratedValue(strategy
=GenerationType.AUTO)
    @Column(name 
= "dept_id", unique = true, nullable = false, insertable = true, updatable = true)
    @DocumentId
    
public Integer getDeptId() {
        
return this.deptId;
    }


    
public void setDeptId(Integer deptId) {
        
this.deptId = deptId;
    }


    @Column(name 
= "dept_no", unique = false, nullable = true, insertable = true, updatable = true, length = 30)
    
public String getDeptNo() {
        
return this.deptNo;
    }


    
public void setDeptNo(String deptNo) {
        
this.deptNo = deptNo;
    }


    @Column(name 
= "dept_name", unique = false, nullable = true, insertable = true, updatable = true, length = 30)
    @Field(name
="name", index=Index.TOKENIZED,store=Store.YES)
    
public String getDeptName() {
        
return this.deptName;
    }


    
public void setDeptName(String deptName) {
        
this.deptName = deptName;
    }

}
         不了解Hibernate映射相关的Annotation的朋友可以到Hibernate的官方网站下载Hibernate Annotation Reference,有http://wiki.redsaga.com/翻译的中文文档。当然,也可以直接使用hbm.xml文件。
        Hibernate Search相关的Annotation主要有两个:
         @Indexed                标识需要进行索引的对象,
         属性        index         指定索引文件的路径
          @Field                     标注在类的get属性上,标识一个索引的Field
          属性       index         指定是否索引,与Lucene相同
                         store         指定是否索引,与Lucene相同
                         name        指定Field的name,默认为类属性的名称
                         analyzer    指定分析器

         另外@IndexedEmbedded  与  @ContainedIn 用于关联类之间的索引
          @IndexedEmbedded有两个属性,一个prefix指定关联的前缀,一个depth指定关联的深度
          如上面两个类中Department类可以通过部门名称name来索引部门,在Employee与部门关联的前缀为dept_,因此可以通过部门名称dept_name来索引一个部门里的所有员工。

2、配置文件
<? xml version='1.0' encoding='UTF-8' ?>
<! DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"
>

< hibernate-configuration >

< session-factory >
    
< property  name ="hibernate.dialect" >
        org.hibernate.dialect.MySQLDialect
    
</ property >
    
< property  name ="hibernate.connection.url" >
        jdbc:mysql://localhost:3306/hise
    
</ property >
    
< property  name ="hibernate.connection.username" > root </ property >
    
< property  name ="hibernate.connection.password" > 123456 </ property >
    
< property  name ="hibernate.connection.driver_class" >
        com.mysql.jdbc.Driver
    
</ property >

    
< property  name ="hibernate.search.default.directory_provider" >
        org.hibernate.search.store.FSDirectoryProvider
    
</ property >
    
< property  name ="hibernate.search.default.indexBase" > e:/index </ property >
    
    
< mapping  class ="com.yehui.Employee"   />
    
< mapping  class ="com.yehui.Department"   />
</ session-factory >

</ hibernate-configuration >
如果使用JPA,配置文件为
<? xml version="1.0" encoding="UTF-8" ?>
< persistence  xmlns ="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation
="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
 version ="1.0" >
    
    
< persistence-unit  name ="jpaPU"  transaction-type ="RESOURCE_LOCAL" >
        
< provider > org.hibernate.ejb.HibernatePersistence </ provider >
        
< class > com.yehui.Department </ class >
        
< class > com.yehui.Employee </ class >
        
< properties >
            
< property  name ="hibernate.connection.driver_class"
                value
="com.mysql.jdbc.Driver"   />
            
< property  name ="hibernate.connection.url"
                value
="jdbc:mysql://localhost:3306/hise"   />
            
< property  name ="hibernate.connection.username"  value ="root"   />
            
< property  name ="hibernate.connection.password"
                value
="123456"   />
            
< property  name ="hibernate.search.default.directory_provider"  
                value
="org.hibernate.search.store.FSDirectoryProvider" />
            
< property  name ="hibernate.search.default.indexBase"  
                value
="e:/index" />
        
</ properties >
    
</ persistence-unit >

</ persistence >
主要就是添加两个属性, hibernate.search.default.directory_provider指定Directory的代理,即把索引的文件保存在硬盘中( org.hibernate.search.store.FSDirectoryProvider)还是内存里( org.hibernate.search.store.RAMDirectoryProvider),保存在硬盘的话 hibernate.search.default.indexBase属性指定索引保存的路径。

3、测试代码
package  com.yehui;

import   static  junit.framework.Assert.assertNotNull;
import   static  junit.framework.Assert.assertTrue;

import  java.util.List;

import  org.apache.lucene.analysis.StopAnalyzer;
import  org.apache.lucene.queryParser.QueryParser;
import  org.hibernate.Query;
import  org.hibernate.Session;
import  org.hibernate.SessionFactory;
import  org.hibernate.Transaction;
import  org.hibernate.cfg.AnnotationConfiguration;
import  org.hibernate.search.FullTextSession;
import  org.hibernate.search.Search;
import  org.junit.After;
import  org.junit.Before;
import  org.junit.BeforeClass;
import  org.junit.Test;

public   class  SearchResultsHibernate  {
    
private static SessionFactory sf = null;
    
private static Session session = null;
    
private static Transaction tx = null;

    @BeforeClass
    
public static void setupBeforeClass() throws Exception {
        sf 
= new AnnotationConfiguration().configure("hibernate.cfg.xml").buildSessionFactory();

        assertNotNull(sf);
    }


    @Before
    
public void setUp() throws Exception {
        session 
= sf.openSession();
        tx 
= session.beginTransaction();
        tx.begin();
    }


    @After
    
public void tearDown() throws Exception {
        tx.commit();
        session.close();
    }


    
public static void tearDownAfterClass() throws Exception {
        
if (sf != null)
            sf.close();
    }


    @Test
    
public void testAddDept() throws Exception {
        Department dept 
= new Department();
        dept.setDeptName(
"Market");
        dept.setDeptNo(
"6000");

        Employee emp 
= new Employee();
        emp.setDept(dept);
        emp.setEmpName(
"Kevin");
        emp.setEmpNo(
"KGP1213");
        emp.setEmpSalary(8000d);
        
        session.save(emp);
    }


    @Test
    
public void testFindAll() throws Exception {
        Query query 
= session.createQuery("from Department");

        List
<Department> deptList = query.list();

        assertTrue(deptList.size() 
> 0);
    }

    
    @Test
    
public void testIndex() throws Exception {
        FullTextSession fullTextSession 
= Search.createFullTextSession(session);
        assertNotNull(session);

        QueryParser parser 
= new QueryParser("name"new StopAnalyzer());
        org.apache.lucene.search.Query luceneQuery 
= parser
                .parse(
"name:Kevin");
        Query hibQuery 
= fullTextSession.createFullTextQuery(luceneQuery,
                Employee.
class);

        List list 
= hibQuery.list();
        assertTrue(list.size() 
> 0);
    }

    
    @Test
    
public void testIndex2() throws Exception {
        FullTextSession fullTextSession 
= Search.createFullTextSession(session);
        assertNotNull(session);

        QueryParser parser 
= new QueryParser("dept_name"new StopAnalyzer());
        org.apache.lucene.search.Query luceneQuery 
= parser
                .parse(
"dept_name:Market");
        Query hibQuery 
= fullTextSession.createFullTextQuery(luceneQuery,
                Employee.
class);

        List list 
= hibQuery.list();
        assertTrue(list.size() 
> 0);
    }

}

测试通过。OK

原文:http://blog.csdn.net/yanghuw/archive/2007/09/30/1808011.aspx

-------------------------------------------------------------------------------------------------------------------------------------

不久前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. <property name="hibernate.search.default.directory_provider">  
  2.           org.hibernate.search.store.FSDirectoryProvider   
  3. </property>  
  4. <property name="hibernate.search.default.indexBase">  
  5.           E:/temp/index   
  6. </property>  

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

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

java 代码
  1. @Indexed(index = "text")   
  2. public class Text implements java.io.Serializable   
  3. {   
  4.     @DocumentId  
  5.     private Integer id;   
  6.   
  7.     private String fileName;   
  8.   
  9.     private String filePath;   
  10.   
  11.     @Field(name = "content", store = Store.NO, index = Index.TOKENIZED, analyzer = @Analyzer(impl = ChineseAnalyzer.class))   
  12.     private String content;   
  13.   
  14.     ......   
  15. }  

其中@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 代码
  1. //获取Session   
  2. Session session = HibernateUtil.getSession();   
  3. //封装Session为FullTextSession   
  4. FullTextSession fullTextSession = Search.createFullTextSession(session);   
  5.   
  6. //开始事务   
  7. Transaction tx = fullTextSession.beginTransaction();   
  8.   
  9. ......   
  10.   
  11. //提交事务   
  12. tx.commit();   
  13. //关闭会话   
  14. fullTextSession.close();  

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

三、检索

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

java 代码
  1. Session session = HibernateUtil.getSession();   
  2. FullTextSession fullTextSession = Search.createFullTextSession(session);   
  3.   
  4. Transaction tx = fullTextSession.beginTransaction();   
  5.   
  6. QueryParser parser = new QueryParser("content"new ChineseAnalyzer());   
  7.   
  8. Query query = fullTextSession.createFullTextQuery(parser.parse(word),   
  9.         Text.class);   
  10.   
  11. List result = query.list();   
  12. for (int i = 0; result != null && i < result.size(); i++)   
  13. {   
  14.     Text pojo = (Text) result.get(i);   
  15.     System.out.println("文件名:" + pojo.getFileName());   
  16.     System.out.println("文件路径:" + pojo.getFilePath());   
  17.     System.out.println();   
  18. }   
  19.   
  20. tx.commit();   
  21. fullTextSession.close();  

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

四、完

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

  • src.zip (5.8 KB)
  • 描述: 源代码与配置文件
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值