`

hibernate Search牛刀小试 (转)

阅读更多
前几天看到Hibernate与Lucene的整合框架Hiberate Search3.0.0.GA版出来了,昨天试这写了一个Demo,感觉用起来的确很方便的,贴出来与大家分享一下。

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
分享到:
评论

相关推荐

    Hibernate Search In Action

    Hibernate Search是一个强大的库,它为Hibernate框架提供了全文搜索的功能。全文搜索是一种强大的信息检索方式,可以让用户通过关键词快速定位到存储在大量数据中的相关内容。Hibernate Search库将全文搜索与...

    Hibernate小试牛刀

    【标题】:“Hibernate小试牛刀” 在Java开发领域,Hibernate是一个非常重要的对象关系映射(ORM)框架,它极大地简化了数据库操作。本篇内容将深入探讨Hibernate的基本概念、安装配置以及简单应用,帮助初学者快速...

    hibernateSearch+demo

    这个“hibernateSearch+demo”项目提供了一个实战示例,帮助开发者理解并应用 Hibernate Search 的核心概念和功能。 在 Hibernate Search 中,主要涉及以下关键知识点: 1. **全文索引**:Hibernate Search 使用 ...

    hibernate Search in action

    《Hibernate Search in Action》这本书深入探讨了Hibernate Search这一强大的全文搜索引擎集成框架,它将全文搜索功能无缝地融入到Java持久层框架Hibernate之中。通过利用Lucene库的强大功能,Hibernate Search为...

    Hibernate Search配置及简单应用

    **Hibernate Search配置及简单应用** Hibernate Search是Hibernate框架的一个扩展,它允许我们在应用程序中实现全文检索功能,使得数据库中的数据可以被快速、高效地搜索。这个功能尤其在处理大量文本数据时非常...

    hibernate search全文索引的创建及查询

    Hibernate Search是Hibernate ORM框架的一个扩展,它允许开发者在Java应用中实现全文搜索功能。这个工具结合了ORM的强大和Lucene搜索引擎的高效,使得数据库中的数据可以被快速、精准地检索。本文将深入探讨如何创建...

    Hibernate搜索框架HibernateSearch.zip

    Hibernate Search的作用是对数据库中的数据进行检索的。它是hibernate对著名的全文检索系统Lucene的一个集成方案,作用在于对数据表中某些内容庞大的字段(如声明为text的字段)建立全文索引,这样通过hibernate ...

    hibernate-search, Hibernate Search.zip

    hibernate-search, Hibernate Search Hibernate 搜索版本:5.8.0. Final - 13-09-2017描述针对Java对象的全文搜索这个项目提供 Hibernate ORM和全文索引服务( 如 Apache Lucene和 Elasticsearch

    hibernate-search-5.5.4 api docset for Dash

    Hibernate Search 是一个强大的全文搜索引擎框架,它将Apache Lucene库集成到Hibernate ORM中,使得在Java应用程序中实现复杂的全文检索和分析功能变得简单。这个"hibernate-search-5.5.4 api docset for Dash"是...

    基于Spring的Hibernate Search全文检索功能示例

    3. **Hibernate Search**:作为Hibernate的一个扩展,Hibernate Search提供了基于Lucene的全文检索功能,使得在数据库中的数据可以被快速、精确地搜索。 **二、集成Hibernate Search** 1. **配置依赖**:首先,你...

    Hibernate Search in action (pdf && code)

    《Hibernate Search in Action》是一本深入探讨Hibernate Search技术的专业书籍,配合源代码一同学习,能够帮助读者更好地理解和应用这项强大的全文检索和分析框架。Hibernate Search是Hibernate ORM的一个扩展,它...

    hibernate search-3.4.0.Final-dist

    《Hibernate Search 3.4.0.Final:深入探索企业级数据检索的利器》 Hibernate Search,作为Hibernate ORM框架的一个强大扩展,为Java开发者提供了一种在持久化数据上进行全文搜索的能力。这个3.4.0.Final版本是...

    hibernate_search.pdf

    标题:hibernate_search.pdf 描述与标签:此文档详细介绍了Hibernate Search的使用与配置,一个为Hibernate ORM提供全文搜索功能的扩展。该文档版本为3.1.0.GA,深入探讨了如何将Apache Lucene集成到Hibernate ORM...

    Hibernate Search 4.4.0.Final API

    Hibernate Search 4.4.0.Final API 帮助文档

    hibernate-search-5.6.0.Alpha3-dist.zip

    《Hibernate Search 5.6.0.Alpha3:深入探索企业级数据检索的利器》 Hibernate Search,作为Java领域中的一款强大、高效的全文搜索引擎,与ORM框架Hibernate紧密结合,为开发者提供了在数据库中进行复杂检索的能力...

    Hibernate Search in Action

    《Hibernate Search in Action》这本书是关于Java开发中利用Hibernate Search框架进行全文检索的权威指南。Hibernate Search是一个在Hibernate ORM之上构建的搜索引擎,它允许开发者在Java应用中实现强大的、数据库...

Global site tag (gtag.js) - Google Analytics