Hibernate Search是基于Lucene的全文检索框架,可以很好的整合Hibernate,实现快速检索实体类。我们今天主要来介绍Hibernate Serach的基础入门。

开发环境准备——使用Maven搭建开发环境

DEMO使用Spring Data JPA(1.10) + Hibernate Search(5.9)来实现。

以下为本次开发的pom.xml文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.itheima</groupId><artifactId>hibernatesearch-demo</artifactId><version>0.0.1-SNAPSHOT</version><properties><hibernate-version>5.2.12.Final</hibernate-version><hibernate-search-version>5.9.1.Final</hibernate-search-version><spring-version>4.2.4.RELEASE</spring-version><jdk-version>1.8</jdk-version></properties><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.0</version><configuration><target>${jdk-version}</target><source>${jdk-version}</source></configuration></plugin></plugins></build><dependencies><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-core</artifactId><version>${hibernate-version}</version></dependency><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-entitymanager</artifactId><version>${hibernate-version}</version></dependency><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-search-orm</artifactId><version>${hibernate-search-version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>${spring-version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>${spring-version}</version></dependency><dependency><groupId>org.hibernate.javax.persistence</groupId><artifactId>hibernate-jpa-2.1-api</artifactId><version>1.0.0.Final</version></dependency><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-jpa</artifactId><version>1.10.4.RELEASE</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.6</version></dependency><!-- IK中文分词器 --><dependency><groupId>cn.bestwu</groupId><artifactId>ik-analyzers</artifactId><version>5.1.0</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.6</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency></dependencies>
</project>

Spring配置文件

Spring整合了JPA以及Spring Data JPA的配置文件

<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsdhttp://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.8.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd"><context:component-scan base-package="com.itheima"></context:component-scan><!--加载外部properties配置文件-->
<context:property-placeholder location="classpath:config.properties"/><!--配置Druid数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /><property name="driverClassName" value="${jdbc.driver}" />
</bean><!-- Spring整合JPA -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"><property name="dataSource" ref="dataSource"/><property name="packagesToScan" value="com.itheima.entity"/><property name="persistenceProviderClass" value="org.hibernate.jpa.HibernatePersistenceProvider"></property><property name="jpaProperties"><props><prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop><prop key="hibernate.show_sql">false</prop><prop key="hibernate.format_sql">false</prop><prop key="hibernate.hbm2ddl.auto">update</prop><!-- 将索引存放在文件系统 --><prop key="hibernate.search.default.directory_provider">filesystem</prop><!-- 指定用于保存索引的目录 --><prop key="hibernate.search.default.indexBase">G:/workspace/free_test/t26/index</prop></props></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"><property name="dataSource" ref="dataSource"/><property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean><!-- 配置Spring Data JPA包扫描自动创建代理对象 -->
<jpa:repositories base-package="com.itheima.repository" entity-manager-factory-ref="entityManagerFactory"transaction-manager-ref="transactionManager"/><!-- 开启声明式事务 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

数据库配置文件

jdbc.url=jdbc:mysql:///demo
jdbc.driver=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=000000

在实体类中开启全文检索

编写实体类

package com.itheima.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;import org.hibernate.annotations.GenericGenerator;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Analyzer;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.FieldBridge;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.NumericField;
import org.hibernate.search.annotations.Store;
import org.wltea.analyzer.lucene.IKAnalyzer;@Entity
@Table(name = "t_product")
// 使用@Indexed表示这个实体类需要创建索引
@Indexed
// 指定使用IK分词器
@Analyzer(impl=IKAnalyzer.class)
public class Product {// 默认使用@Id注解修饰的字段作为索引的唯一标识符@Id@GenericGenerator(name = "sysuuid", strategy = "uuid")@GeneratedValue(generator = "sysuuid")private String id;// 默认为字段建立索引、进行分词(分析)、不存储@Field(store=Store.YES)private String name; // 商品名称@Field(store=Store.YES)private String description; // 商品描述@Field(store=Store.YES)// 如果是数字字段,需要使用@NumericField进行修饰@NumericField(forField="price")private Double price; // 商品价格@Field(store=Store.YES)private String catelog; // 商品分类public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}public Double getPrice() {return price;}public void setPrice(Double price) {this.price = price;}public String getCatelog() {return catelog;}public void setCatelog(String catelog) {this.catelog = catelog;}@Overridepublic String toString() {return "Product [id=" + id + ", name=" + name + ", description=" + description + ", price=" + price+ ", catelog=" + catelog + "]";}
}

编写DAO接口

package com.itheima.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.itheima.entity.Product;public interface ProductRepository extends JpaRepository<Product, String>{}

编写Service接口

package com.itheima.service;
import java.util.List;import com.itheima.entity.Product;public interface ProductService {void save(Product product);List fullTextQuery(String[] fields, String keyword);List rangeQuery(String fields, double from, double to);
}

编写Service实现

package com.itheima.service;
import java.util.List;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.Search;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.itheima.entity.Product;
import com.itheima.repository.ProductRepository;@Service
@Transactional
public class ProductServiceImpl implements ProductService {@Autowiredprivate ProductRepository productRepository;@Autowiredprivate EntityManager entityManager;@Overridepublic void save(Product product) {productRepository.save(product);}/*** 根据关键字进行全文检索*/@Overridepublic List fullTextQuery(String[] fields, String keyword) {FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Product.class).get();org.apache.lucene.search.Query luceneQuery = qb.keyword().onFields(fields).matching(keyword).createQuery();javax.persistence.Query jpaQuery = fullTextEntityManager.createFullTextQuery(luceneQuery, Product.class);return jpaQuery.getResultList();}/*** 根据数值范围进行检索*/@Overridepublic List rangeQuery(String field, double from, double to) {FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Product.class).get();org.apache.lucene.search.Query luceneQuery = qb.range().onField(field).from(from).to(to).createQuery();javax.persistence.Query jpaQuery = fullTextEntityManager.createFullTextQuery(luceneQuery, Product.class);return jpaQuery.getResultList();}
}

测试代码:
package com.itheima.service.test;
import java.util.List;
import javax.persistence.EntityManager;
import org.apache.commons.lang.math.RandomUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4Cla***unner;
import com.itheima.entity.Product;
import com.itheima.service.ProductService;

// 整合Spring Junitbr/>@RunWith(SpringJUnit4Cla***unner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class ProductServiceTest {

@Autowired
private ProductService productService;/**
* 创建测试数据,Hiberante Search会自动创建索引
*/
@Test
public void saveTest01() {for(int i = 0; i < 100; ++i) {Product product = new Product();product.setCatelog("手机");product.setDescription("小米 红米5A 全网通版 3GB+32GB 香槟金 移动联通电信4G手机 双卡双待");product.setName("红米5A" + i);product.setPrice(RandomUtils.nextDouble() * 100 % 100);productService.save(product);}
}@Test
public void fullTextQueryTest01() {List list = productService.fullTextQuery("catelog,description,name".split(","), "移动");for (Object object : list) {System.out.println(object);}
}@Test
public void rangeQueryTest01() {List list = productService.rangeQuery("price", 10.0D, 20D);for (Object object : list) {System.out.println(object);}
}

}

转载于:https://blog.51cto.com/13587708/2103909

Hibernate Serach 5.9全文检索快速入门相关推荐

  1. (转)Hibernate快速入门

    http://blog.csdn.net/yerenyuan_pku/article/details/64209343 Hibernate框架介绍 什么是Hibernate 我们可以从度娘上摘抄这样有 ...

  2. Hibernate 快速入门

    原视频内容以及资料来自 b 站:https://www.bilibili.com/medialist/play/ml1025729445/p1 hibernate 在 idea 中文件快速生成博客:h ...

  3. 零基础快速入门SpringBoot2.0教程 (三)

    一.SpringBoot Starter讲解 简介:介绍什么是SpringBoot Starter和主要作用 1.官网地址:https://docs.spring.io/spring-boot/doc ...

  4. 一文快速入门分库分表中间件 Sharding-JDBC (必修课)

    书接上文 <一文快速入门分库分表(必修课)>,这篇拖了好长的时间,本来计划在一周前就该写完的,结果家庭内部突然人事调整,领导层进行权利交接,随之宣布我正式当爹,紧接着家庭地位滑落至第三名, ...

  5. Lucene第一篇【介绍Lucene、快速入门】

    tags: Lucene 什么是Lucene?? Lucene是apache软件基金会发布的一个开放源代码的全文检索引擎工具包,由资深全文检索专家Doug Cutting所撰写,它是一个全文检索引擎的 ...

  6. Castle Active Record for .NET2.0快速入门示例

    一.创建Web工程 创建一个Web站点或者Web应用程序,添加对Castle.ActiveRecord.dll的引用. 二.创建需要持久化的业务实体 在.NET2.0下,由于引入了泛型,创建业务实体比 ...

  7. struts2教程--快速入门

    Struts2框架介绍 1.三大框架 : 是企业主流 JavaEE开发的一套架构 Struts2 + Spring + Hibernate 2. 什么是框架?为什么要学框架 ? 框架 是 实现部分功能 ...

  8. 分库分表介绍和Sharding-JDBC快速入门

    1.分库分表介绍 垂直分表:可以把一个宽表的字段按访问频次.是否是大字段的原则拆分为多个表,这样既能使业务清晰,还能提升部分性能.拆分后,尽量从业务角度避免联查,否则性能方面将得不偿失. 比如我们可以 ...

  9. 尚硅谷-SpringBoot高级-检索-Elasticsearch快速入门

    前面我们安装好了ElasticSearch,我以后就简称他为ES,而一些人还不知道基本的使用,那我们接下来做一个快速入门,了解一下他的使用方法,以及一些基本概念,方便我们后来整合,那么要学习ES最好的 ...

  10. SpringBoot约定大于配置的特性解读 SpringBoot快速入门

    SpringBoot约定大于配置 Spring官方网站本身使用Spring框架开发,随着功能以及业务逻辑的日益复杂,应用伴随着大量的XML配置文件以及复杂的Bean依赖关系.随着Spring 3.0的 ...

最新文章

  1. Centos7安装Nginx+PHP
  2. ORM对mysql数据库中数据进行操作报错解决
  3. Java Servlet工作原理问答
  4. 不要和别人说你一定要干什么
  5. javascript 定义类(转载)
  6. 跑得好好的Java进程,怎么突然就瘫痪了?
  7. 第十届常州国际动漫艺术周
  8. servlet中使用db4o
  9. ubuntu中安装flash播放器
  10. android 添加蒙版实现护眼模式(夜间模式)
  11. 微信端和手机qq浏览器输入框不能输入汉字
  12. 零基础学FPGA(四):IP是什么东西(什么是软核,硬核)
  13. 干得好也要说得好| 这样向领导汇报,让你在职场上如鱼得水
  14. 古诗词 中文 分词 自动化
  15. Fedora 使用 yaourt
  16. 基于Matlab的静电场仿真实验--求均匀带电球壳的电场
  17. 《zw版·Halcon-delphi系列原创教程》 Halcon分类函数012,polygon,多边形
  18. 11. kafka重试机制解读
  19. DOS(bat) 字符串替换原理
  20. 维控触摸屏通过U盘升级工程教程

热门文章

  1. 如何把PPT文件压缩到最小
  2. 【数据产品案例】美团外卖O2O的用户画像实践
  3. 年轻人,你应该拒绝奶头乐
  4. 离职,第 10 天,有点心酸。。。
  5. julia集 matlab代码,Mandelbrot集和Julia集的分形图之matlab实现.docx
  6. 家里宽带628连不上_宽带连接错误628连接被远程计算机终止是什么意思 - 卡饭网...
  7. 学习笔记 Tianmao 篇 SwipeRefreshLayoyt 下拉刷新 控件 使用
  8. MSP430开发环境配置
  9. 如何使用一键回录游戏视频
  10. 主存空间的分配和回收实验报告