Hibernate search5.3.0 Full-text search integrated into spring data JPA

Source: Internet
Author: User

Hibernate search I will not say more, it is based on Lucene full-text Search tool, remember when the university contacted the Compass full-text Search tool, and then did not use, and then later this guy does not update, So hibernate has launched its own lucene-based full-text Search tool which is the guy hibernate search.

Needless to say that the natural advantage is seamless and hibernate integration and even do not need any configuration, has been in the update, recently want to add search function in their blog, I would like to use the more warm SOLR, find a half-day information or give up, used in my blog a bit blowing out, That's why hibernate search is locked down, simple, and doesn't require any configuration for hibernate JPA, although I'm using spring data JPA but I don't think it will affect its use.

Nonsense will not say, we get to the point, starting from the configuration:

1.persistence.xml file included:

<property name= "Hibernate.search.default.directory_provider" value= "filesystem"/>
<property name= "Hibernate.search.default.indexBase" value= "e:/index"/>
If it is a Linux system to change the path, configuration, is not very simple, other places do not need any changes.

2. Entities:

It doesn't have to be explained, you want to do a search on that entity to configure that entity, it's plain to add some annotations.

I wrote briefly, as for the meaning of the annotations we find on the Internet.

@Analyzer (Impl=smartchineseanalyzer.class)
public class Posts implements Java.io.Serializable {

@Id//Do not need to add anything here, if you use Hibernate to do the persistence layer need to add @documentid this annotation
Public Integer getId () {
return ID;
public void SetId (Integer id) {
This.id = ID;

@Column (name = "Post_title", nullable = false,length=1000)
@Boost (2)
Public String Getptitle () {
return ptitle;
public void Setptitle (String ptitle) {
This.ptitle = Ptitle;

Public String getcontent () {
return content;
public void SetContent (String content) {
this.content = content;

Do you need me to explain it, I don't think I need it.

As simple as this, add a few annotations, and the system will automatically generate the index file at run time.

3. Search service:

This is mostly on the service layer, because I'm using spring data JPA

@Service ("Postservice")
public class Postserviceimpl implements postservice{

private entitymanagerfactory emf;

Here I inject in this implementation class inside the Applicationcontext.xml configuration of the entitymanagerfactory, I think you should understand these

public queryresult<posts> search (int nowpage,int size,string KeyWord) { queryresult<posts> QueryResult = new queryresult<posts> (); Entitymanager em = Emf.createentitymanager (); Fulltextentitymanager Fmanager = Search.getfulltextentitymanager (EM); QueryBuilder QB = Fmanager.getsearchfactory (). Buildquerybuilder (). forentity (Posts.class). get (); Query q = Qb.keyword (). Onfields ("Ptitle", "description", "content"). Matching (keyword). createquery (); FullTextQuery FQ = fmanager.createfulltextquery (q, Posts.class); Queryresult.settotalrecord (Fq.getResultSize ()); list<posts> re = Fq.setfirstresult (nowpage). Setmaxresults (size). Getresultlist (); re = Hightlight (q, Re, Posts.class, NULL, "Ptitle", "description", "content"); Queryresult.setresultlist (re); return queryresult;} 
/*** @param org.apache.lucene.search.Query lucenequery * @param searchresults Search Result set * @param searchresultclass search knot Fruit type * @param excludefields to exclude highlighted fields * @param fieldnames fields that need to be highlighted * @return highlighted searchresults */private < E> list<e> hightlight (Query lucenequery, list<e> searchresults, class<e> SearchResultClass, List <String> excludefields, String ... fieldnames) {Simplehtmlformatter formatter = new Simplehtmlformatter ("<        B><font color=\ "red\" > "," </font></b> ");        Queryscorer queryscorer = new Queryscorer (lucenequery);        Highlighter highlighter = new highlighter (formatter, queryscorer);                 Analyzer Analyzer = new Smartchineseanalyzer (); for (E e:searchresults) {for (String fieldname:fieldnames) {if (null! = EX                Cludefields && excludefields.contains (fieldName)) {continue;                     }            Object fieldvalue = Reflectionutils.invokemethod (Beanutils.getpropertydescriptor (Searchresultclass, FieldName)                                 . Getreadmethod (), E);                                 String hightlightfieldvalue = null; if (fieldvalue instanceof String) {try {Hightlightfieldvalu                    E = highlighter.getbestfragment (Analyzer, FieldName, string.valueof (Fieldvalue));                    } catch (Exception E1) {e1.printstacktrace (); } reflectionutils.invokemethod (Beanutils.getpropertydescriptor (Searchresultclass, fieldName). getWriteMe                                    Thod (), E, hightlightfieldvalue);    }}} return searchresults; }

Explanation: Onfields ("Ptitle", "description", "content") These are the fields you want to retrieve, and several are written.

This added to the pagination effect, highlighting the effect, this code I also found on the Internet to modify a bit, if who has better can leave a message to share a bit.

package com.weirblog.fenye;import java.util.list;/** * Query result set, including data and total * @author  Db2admin * * @param <T> */public class Queryresult<t> {/** query data List **/private list<t> resultlist;/** Total number of queries **/private int totalrecord;public list<t> getresultlist () {return resultlist;} public void Setresultlist (list<t> resultlist) {this.resultlist = resultlist;} public int Gettotalrecord () {return totalrecord;} public void Settotalrecord (int totalrecord) {This.totalrecord = Totalrecord;}} 
Package Com.weirblog.fenye;import java.util.list;/** * Paging data wrapper, including paging information and List data */public class Pageview<t> {/** paging data * */private list<t> records;/** page start index and end index **/private PageIndex pageindex;/** total pages **/private int totalpage = 1;/** per page Shows the number of records **/private int maxresult = 10;/** current page **/private int currentpage = 1;/** Total records **/private int totalrecord;/** How many pages per display Must be guaranteed to be greater than 3 pages, guaranteeing that both left and right links can be used **/private int viewpagecount = 10;/** to get the start index of the record **/public int getfirstresult () {return (This.curre NTPAGE-1);//return (this.currentpage-1) * THIS.MAXRESULT;} public int Getviewpagecount () {return viewpagecount;} public void Setviewpagecount (int viewpagecount) {this.viewpagecount = Viewpagecount;} Public PageView (int maxresult, int currentpage) {This.maxresult = Maxresult;this.currentpage = (currentpage <= 0? 1: CurrentPage);} Public PageView (int currentpage) {this.currentpage = (currentpage <= 0? 1:currentpage);} public void Setqueryresult (queryresult<t> qr) {Settotalrecord (Qr.gettotalrecord()); Setrecords (Qr.getresultlist ());} public int Gettotalrecord () {return totalrecord;} public void Settotalrecord (int totalrecord) {This.totalrecord = Totalrecord;settotalpage (this.totalrecord% This.maxresult = = 0? This.totalrecord/this.maxresult:this.totalrecord/this.maxresult + 1);} Public list<t> GetRecords () {return records;} public void Setrecords (List<t> records) {this.records = records;} Public PageIndex Getpageindex () {return PageIndex;} public int gettotalpage () {return totalpage;} public void settotalpage (int totalpage) {this.totalpage = Totalpage;this.pageindex = Pageindex.getpageindex ( Viewpagecount, currentpage,totalpage);} public int Getmaxresult () {return maxresult;} public int getcurrentpage () {return currentpage;}}
I'm not going to explain these wrappers about paging.

4.controller Layer:

@RequestMapping ("/search") public String Search (Integer page,string keyword,model Model) {pageview<posts> PageView = new Pageview<posts> (2, Page!=null page:1);p Ageview.setqueryresult (Postservice.search ( Pageview.getfirstresult (), Pageview.getmaxresult (), KeyWord)) Model.addattribute ("PageView", PageView); return "/ Search ";}
this should not have to explain anything.

And some of them are jar bags. I'm using the latest stable version 5.3.0







Repeat, remove.

Hibernate needs to be up-to-date, too 4.3.10

Lucene needs:

Lucene these hibernate search packages do not have their own to the Lucene official online download, there is a way to build a MAVEN project to join:

<dependency>   <groupId>org.hibernate</groupId>   <artifactid>hibernate-search-orm </artifactId>   <version>5.3.0.Final</version></dependency>
That's how it's done. The problem of missing jar packages is very nonsense.

Finally, let's look at the effect:

It's OK.

Hibernate search5.3.0 Full-text search integrated into spring data JPA

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.