`
yanghuw
  • 浏览: 13280 次
  • 来自: ...
文章分类
社区版块
存档分类
最新评论

Hibernate Search牛刀小试

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

1、创建POJO
java 代码
 
  1. @Entity  
  2. @Table(name = "employee", catalog = "hise", uniqueConstraints = {})  
  3. @Indexed(index = "indexes/employee")  
  4. public class Employee implements java.io.Serializable {  
  5.     private static final long serialVersionUID = 7794235365739814541L;  
  6.     private Integer empId;  
  7.     private String empName;  
  8.     private Department dept;  
  9.     private String empNo;  
  10.     private Double empSalary;  
  11.   
  12.     // Constructors  
  13.   
  14.     /** default constructor */  
  15.     public Employee() {  
  16.     }  
  17.   
  18.     /** minimal constructor */  
  19.     public Employee(Integer empId) {  
  20.         this.empId = empId;  
  21.     }  
  22.   
  23.     /** full constructor */  
  24.     public Employee(Integer empId, String empName,  
  25.             String empNo, Double empSalary) {  
  26.         this.empId = empId;  
  27.         this.empName = empName;  
  28.         this.empNo = empNo;  
  29.         this.empSalary = empSalary;  
  30.     }  
  31.   
  32.     // Property accessors  
  33.     @Id  
  34.     @GeneratedValue(strategy = GenerationType.AUTO)  
  35.     @Column(name = "emp_id", unique = true, nullable = false, insertable = true, updatable = true)  
  36.     @DocumentId  
  37.     public Integer getEmpId() {  
  38.         return this.empId;  
  39.     }  
  40.   
  41.     public void setEmpId(Integer empId) {  
  42.         this.empId = empId;  
  43.     }  
  44.   
  45.     @Column(name = "emp_name", unique = false, nullable = true, insertable = true, updatable = true, length = 30)  
  46.     @Field(name="name", index=Index.TOKENIZED, store=Store.YES)  
  47.     public String getEmpName() {  
  48.         return this.empName;  
  49.     }  
  50.   
  51.     public void setEmpName(String empName) {  
  52.         this.empName = empName;  
  53.     }  
  54.   
  55.     @Column(name = "emp_no", unique = false, nullable = true, insertable = true, updatable = true, length = 30)  
  56.     @Field(index=Index.UN_TOKENIZED)  
  57.     public String getEmpNo() {  
  58.         return this.empNo;  
  59.     }  
  60.   
  61.     public void setEmpNo(String empNo) {  
  62.         this.empNo = empNo;  
  63.     }  
  64.   
  65.     @Column(name = "emp_salary", unique = false, nullable = true, insertable = true, updatable = true, precision = 7)  
  66.     public Double getEmpSalary() {  
  67.         return this.empSalary;  
  68.     }  
  69.   
  70.     public void setEmpSalary(Double empSalary) {  
  71.         this.empSalary = empSalary;  
  72.     }  
  73.   
  74.     @ManyToOne(cascade = CascadeType.ALL)  
  75.     @JoinColumn(name="dept_id")  
  76.     @IndexedEmbedded(prefix="dept_")  
  77.     public Department getDept() {  
  78.         return dept;  
  79.     }  
  80.   
  81.     public void setDept(Department dept) {  
  82.         this.dept = dept;  
  83.     }  
  84. }  
java 代码
 
  1. @Entity  
  2. @Table(name = "department", catalog = "hise", uniqueConstraints = {})  
  3. @Indexed(index="indexes/department")  
  4. public class Department implements java.io.Serializable {  
  5.     private static final long serialVersionUID = 7891065193118612907L;  
  6.     private Integer deptId;  
  7.     private String deptNo;  
  8.     private String deptName;  
  9.     private List<Employee> empList;  
  10.   
  11.     // Constructors  
  12.   
  13.     @OneToMany(mappedBy="dept")  
  14.     @ContainedIn  
  15.     public List<Employee> getEmpList() {  
  16.         return empList;  
  17.     }  
  18.   
  19.     public void setEmpList(List<Employee> empList) {  
  20.         this.empList = empList;  
  21.     }  
  22.   
  23.     /** default constructor */  
  24.     public Department() {  
  25.     }  
  26.   
  27.     /** minimal constructor */  
  28.     public Department(Integer deptId) {  
  29.         this.deptId = deptId;  
  30.     }  
  31.   
  32.     /** full constructor */  
  33.     public Department(Integer deptId, String deptNo, String deptName) {  
  34.         this.deptId = deptId;  
  35.         this.deptNo = deptNo;  
  36.         this.deptName = deptName;  
  37.     }  
  38.   
  39.     // Property accessors  
  40.     @Id  
  41.     @GeneratedValue(strategy=GenerationType.AUTO)  
  42.     @Column(name = "dept_id", unique = true, nullable = false, insertable = true, updatable = true)  
  43.     @DocumentId  
  44.     public Integer getDeptId() {  
  45.         return this.deptId;  
  46.     }  
  47.   
  48.     public void setDeptId(Integer deptId) {  
  49.         this.deptId = deptId;  
  50.     }  
  51.   
  52.     @Column(name = "dept_no", unique = false, nullable = true, insertable = true, updatable = true, length = 30)  
  53.     public String getDeptNo() {  
  54.         return this.deptNo;  
  55.     }  
  56.   
  57.     public void setDeptNo(String deptNo) {  
  58.         this.deptNo = deptNo;  
  59.     }  
  60.   
  61.     @Column(name = "dept_name", unique = false, nullable = true, insertable = true, updatable = true, length = 30)  
  62.     @Field(name="name", index=Index.TOKENIZED,store=Store.YES)  
  63.     public String getDeptName() {  
  64.         return this.deptName;  
  65.     }  
  66.   
  67.     public void setDeptName(String deptName) {  
  68.         this.deptName = deptName;  
  69.     }  
  70. }  
       不了解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 代码
 
  1. <?xml version='1.0' encoding='UTF-8'?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC  
  3.           "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
  4.           "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  5.   
  6. <hibernate-configuration>  
  7.   
  8. <session-factory>  
  9.     <property name="hibernate.dialect">  
  10.         org.hibernate.dialect.MySQLDialect  
  11.     </property>  
  12.     <property name="hibernate.connection.url">  
  13.         jdbc:mysql://localhost:3306/hise  
  14.     </property>  
  15.     <property name="hibernate.connection.username">root</property>  
  16.     <property name="hibernate.connection.password">123456</property>  
  17.     <property name="hibernate.connection.driver_class">  
  18.         com.mysql.jdbc.Driver  
  19.     </property>  
  20.   
  21.     <property name="hibernate.search.default.directory_provider">  
  22.         org.hibernate.search.store.FSDirectoryProvider  
  23.     </property>  
  24.     <property name="hibernate.search.default.indexBase">e:/index</property>  
  25.       
  26.     <mapping class="com.yehui.Employee" />  
  27.     <mapping class="com.yehui.Department" />  
  28. </session-factory>  
  29.   
  30. </hibernate-configuration>  

如果使用JPA,配置文件为
xml 代码
 
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <persistence xmlns="http://java.sun.com/xml/ns/persistence"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/persistence  
  5.     http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">  
  6.       
  7.     <persistence-unit name="jpaPU" transaction-type="RESOURCE_LOCAL">  
  8.         <provider>org.hibernate.ejb.HibernatePersistence</provider>  
  9.         <class>com.yehui.Department</class>  
  10.         <class>com.yehui.Employee</class>  
  11.         <properties>  
  12.             <property name="hibernate.connection.driver_class"  
  13.                 value="com.mysql.jdbc.Driver" />  
  14.             <property name="hibernate.connection.url"  
  15.                 value="jdbc:mysql://localhost:3306/hise" />  
  16.             <property name="hibernate.connection.username" value="root" />  
  17.             <property name="hibernate.connection.password"  
  18.                 value="123456" />  
  19.             <property name="hibernate.search.default.directory_provider"   
  20.                 value="org.hibernate.search.store.FSDirectoryProvider"/>  
  21.             <property name="hibernate.search.default.indexBase"   
  22.                 value="e:/index"/>  
  23.         </properties>  
  24.     </persistence-unit>  
  25.   
  26. </persistence>  
       主要就是添加两个属性,hibernate.search.default.directory_provider指定Directory的代理,即把索引的文件保存在硬盘中(org.hibernate.search.store.FSDirectoryProvider)还是内存里(org.hibernate.search.store.RAMDirectoryProvider),保存在硬盘的话hibernate.search.default.indexBase属性指定索引保存的路径。

3、测试代码
java 代码
 
  1. public class SearchResultsHibernate {  
  2.     private static SessionFactory sf = null;  
  3.     private static Session session = null;  
  4.     private static Transaction tx = null;  
  5.   
  6.     @BeforeClass  
  7.     public static void setupBeforeClass() throws Exception {  
  8.         sf = new AnnotationConfiguration().configure("hibernate.cfg.xml").buildSessionFactory();  
  9.   
  10.         assertNotNull(sf);  
  11.     }  
  12.   
  13.     @Before  
  14.     public void setUp() throws Exception {  
  15.         session = sf.openSession();  
  16.         tx = session.beginTransaction();  
  17.         tx.begin();  
  18.     }  
  19.   
  20.     @After  
  21.     public void tearDown() throws Exception {  
  22.         tx.commit();  
  23.         session.close();  
  24.     }  
  25.   
  26.     public static void tearDownAfterClass() throws Exception {  
  27.         if (sf != null)  
  28.             sf.close();  
  29.     }  
  30.   
  31.     @Test  
  32.     public void testAddDept() throws Exception {  
  33.         Department dept = new Department();  
  34.         dept.setDeptName("Market");  
  35.         dept.setDeptNo("6000");  
  36.   
  37.         Employee emp = new Employee();  
  38.         emp.setDept(dept);  
  39.         emp.setEmpName("Kevin");  
  40.         emp.setEmpNo("KGP1213");  
  41.         emp.setEmpSalary(8000d);  
  42.           
  43.         session.save(emp);  
  44.     }  
  45.   
  46.     @Test  
  47.     public void testFindAll() throws Exception {  
  48.         Query query = session.createQuery("from Department");  
  49.   
  50.         List<Department> deptList = query.list();  
  51.   
  52.         assertTrue(deptList.size() > 0);  
  53.     }  
  54.       
  55.     @Test  
  56.     public void testIndex() throws Exception {  
  57.         FullTextSession fullTextSession = Search.createFullTextSession(session);  
  58.         assertNotNull(session);  
  59.   
  60.         QueryParser parser = new QueryParser("name"new StopAnalyzer());  
  61.         org.apache.lucene.search.Query luceneQuery = parser  
  62.                 .parse("name:Kevin");  
  63.         Query hibQuery = fullTextSession.createFullTextQuery(luceneQuery,  
  64.                 Employee.class);  
  65.   
  66.         List list = hibQuery.list();  
  67.         assertTrue(list.size() > 0);  
  68.     }  
  69. }  

    测试通过。OK
分享到:
评论
4 楼 qinliyi123 2008-09-24  
不好意思啊??
我也在测试hibernate search ,我是把他和spring结合起来用的;但是在测试时,类的索引是建立了,也随着HIBERNATE另外的表变化而变化,就是在测试
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);  
    }  
  查询类的时候,org.apache.lucene.search.Query  这个对象一直是空,我用Query .tosting()打印不出值来??所以后面的查询就不会得到查询结果。能否给我解释下我错在什么地方吗???
我的联系方式qq  354109045
在此先谢谢了。
3 楼 simen_net 2008-05-23  
不好意思 问个简单的问题 使用你的代码后在
@Table(name = "employee", catalog = "hise", uniqueConstraints = {})
提示 the table employee can not be found on databases
2 楼 suxy 2007-09-30  
个人感觉hibernate search的优势在于非常简单,非常便捷地支持集群

感觉compass的优势在于通用性好,基本上所有的orm和jdbc都支持,hibernate search只支持hibernate和jpa.另外compass为索引的存储也提供了更多的选择。


hibernate search我只看过文档,compass只看过文档目录,不知道说的是否正确,呵呵。
1 楼 dengyin2000 2007-09-30  
LZ, 知道compass这个项目吗?  我想知道这个跟compass比 有什么优势。

相关推荐

Global site tag (gtag.js) - Google Analytics