(對於項目環境配置,一直沒怎麼看過。此次經歷裏從基礎環境搭建到hibernate search示例的完成)html
1.首先建立project,選擇了web project。java
2.導入hibernate search所須要的包,(根據官方指南導入必須包和部分須要的其餘組件包)具體以下:web
--hibernate search導入包提示的必須包,具體是否必須未驗證 antlr-2.7.7 avro-1.7.5 commons-compress-1.5 dom4j-1.6.1 hibernate-commons-annotations-4.0.4.Final hibernate-core-4.3.1.Final jackson-core-asl-1.9.12 jackson-mapper-asl-1.9.12 jandex-1.1.0.Final javassist-3.18.1-GA jboss-logging-3.1.3.GA jboss-logging-annotations-1.2.0.Beta1 lucene-core-3.6.2 paranamer-2.3 slf4j-api-1.6.1 xml-apis-1.3.03 --jpa須要的包(不知道jms,jsr,jta是否是須要的) hibernate-jpa-2.1-api-1.0.0.Final jms-1.1 jsr250-api-1.0 jta-1.1 --hibernate search引擎,映射 hibernate-search-engine-4.5.0.Final hibernate-search-orm-4.5.0.Final --db2 jdbc和lincense db2jcc db2jcc_license_cu --junit junit-4.8.1
(2014.04.02 jms,jsr,jta是不須要的)sql
3.全部的庫導入完成後,開始配置hibernate,此處選擇XML來配置,在src目錄下新建hibernate.cfg.xml文件shell
基本配置:數據庫
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="hibernate.dialect">org.hibernate.dialect.DB2Dialect</property> <property name="hibernate.connection.driver_class"> com.ibm.db2.jcc.DB2Driver </property> <property name="hibernate.connection.url"> jdbc:db2://IP地址/數據庫名</property> <property name="hibernate.connection.username">USER</property> <property name="hibernate.connection.password">PASSWORD</property> <property name="hibernate.search.default.directory_provider"> org.hibernate.search.store.impl.FSDirectoryProvider </property> <property name="hibernate.search.default.indexBase"> d:\lucene\indexs </property> <mapping class="hst.first.template.entity.Book" /> </session-factory> </hibernate-configuration>
此處沒使用官方教程中的directory_provider和indexBase配置,官方配置也能正常使用。apache
show_sql 顯示查詢語句 format_sql 格式化查詢語句 dialect 數據庫方言 connection.driver_class JDBC數據庫驅動 connection.url JDBC數據庫鏈接地址 connection.username 數據庫鏈接用戶名 connection.password 數據庫鏈接密碼 search.default.directory_provider 全文檢索緩存方式 search.default.indexBase 緩存路徑 mapping class = 「」 數據庫表映射
PS:hibernate.search.default.directory_provider指定Directory的代理,即把索引的文件保存在硬盤中(org.hibernate.search.store.impl.FSDirectoryProvider)仍是內存裏(org.hibernate.search.store.impl.RAMDirectoryProvider),保存在硬盤的話hibernate.search.default.indexBase屬性指定索引保存的路徑。api
4.建立Book實體類,並增長相應的hibernate search所需註解緩存
package hst.first.template.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.search.annotations.Analyze; import org.hibernate.search.annotations.DateBridge; 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.Resolution; import org.hibernate.search.annotations.Store; @Entity @Indexed public class Book { private String id; private String title; private String subtitle; private String author; private Date publicationDate; /** default constructor */ public Book() { } public Book(String id, String title, String subtitle, String author, Date publicationDate) { this.id = id; this.title = title; this.subtitle = subtitle; this.author = author; this.publicationDate = publicationDate; } // Property accessors @Id @Column(name = "ID", length = 100) @DocumentId public String getId() { return this.id; } public void setId(String id) { this.id = id; } @Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO) @Column(name = "TITLE", length = 200) public String getTitle() { return this.title; } public void setTitle(String title) { this.title = title; } @Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO) @Column(name = "SUBTITLE", length = 200) public String getSubtitle() { return this.subtitle; } public void setSubtitle(String subtitle) { this.subtitle = subtitle; } @Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO) @Column(name = "AUTHOR", length = 200) public String getAuthor() { return this.author; } public void setAuthor(String author) { this.author = author; } @Field(index=Index.YES, analyze=Analyze.NO, store=Store.NO) @DateBridge(resolution=Resolution.DAY) @Temporal(TemporalType.DATE) @Column(name = "PUBLICATION_DATE", length = 10) public Date getPublicationDate() { return this.publicationDate; } public void setPublicationDate(Date publicationDate) { this.publicationDate = publicationDate; } }
須要增長的註解:bash
須要檢索的實體類增長 @Indexed 主鍵增長 @Id 須要檢索的字段增長 @Field 和相關屬性(默認屬性如本例) 對非文本格式字段檢索時,須要進行轉換 (轉換註解方式如本例) 格式轉換相關內容詳見: http://docs.jboss.org/hibernate/search/4.5/reference/en-US/html_single/#search-mapping-bridge
PS:本例測試中(ejb3 自動生成)默認實體註解 @Table 存在時,junit測試異常。去掉@Table以後能夠正常使用
5.增長junit測試類:
package hst.first.template.action; import hst.first.template.entity.Book; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.search.FullTextSession; import org.hibernate.search.Search; import org.hibernate.search.SearchFactory; import org.hibernate.search.query.dsl.QueryBuilder; import org.hibernate.service.ServiceRegistry; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class HibernateSearchTest { private static SessionFactory sf = null; private static Session session = null; private static Transaction tx = null; @BeforeClass public static void setupBeforeClass() throws Exception{ StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder(); Configuration cf = new Configuration(); cf.configure("hibernate.cfg.xml"); ServiceRegistry serviceRegistry = serviceRegistryBuilder.applySettings(cf.getProperties()).build(); sf = cf.buildSessionFactory(serviceRegistry); assertNotNull(sf); } @Before public void setup() throws Exception { session = sf.openSession(); tx = session.beginTransaction(); } @After public void tearDown() throws Exception { tx.commit(); session.close(); } @AfterClass public static void tearDownAfterClass() throws Exception { if(sf !=null){ sf.close(); } } private static void assertNotNull(Object obj) throws Exception{ if(obj == null){ throw new NullPointerException(); } } //@Test public void testAdd() throws Exception{ Book book = new Book(); book.setAuthor("村上春樹"); book.setSubtitle("異戀"); book.setTitle("死不過十天半月"); book.setId("7"); Calendar timeMaker = Calendar.getInstance(); timeMaker.set(2005, 06, 31); book.setPublicationDate(timeMaker.getTime()); session.save(book); } @Test public void testFullTextSession() throws Exception{ System.out.println(session==null); FullTextSession fullTextSession = Search.getFullTextSession(session); fullTextSession.createIndexer().startAndWait(); SearchFactory sf = fullTextSession.getSearchFactory(); QueryBuilder qb = sf.buildQueryBuilder().forEntity(Book.class).get(); org.apache.lucene.search.Query luceneQuery = qb.keyword().onFields("author","title","subtitle").matching("銀河").createQuery(); // QueryParser parser = new QueryParser(Version.LUCENE_36, "author", new StopAnalyzer(Version.LUCENE_36)); // org.apache.lucene.search.Query luceneQuery = parser // .parse("author:亦舒"); Query hibQuery = fullTextSession.createFullTextQuery(luceneQuery); List list = hibQuery.list(); assertNotNull(list); for(Object obj:list){ Book book = (Book)obj; System.out.println("書名:"+book.getSubtitle()+"\n 副標題:"+book.getTitle()+"\n 做者:"+book.getAuthor()); } } }
5.1在hibernate 4.0中sessionFactory獲取方式發生了一些改變,如本例@BeforeClass中所寫
5.2在Test中寫有增長數據進庫的測試。只是爲了測試數據庫鏈接狀況
5.3在testFullTextSession()的測試中,測試了hibernate search的基礎查詢。fullTextSession.createIndexer().startAndWait(); 會在hibernate配置的路徑中生成全文索引須要的文件。
5.4在測試中方法中註釋掉的 StopAnalyzer()部分是關於解析器的,具體未解。解析器能夠自定義。解析器的使用須要參考官方說明文檔。
PS:在fullTextSession.createIndexer().startAndWait(); 時會自動進行從新從數據庫中獲取全部數據重建索引數據。若是直接使用fullTextSession.getSearchFactory(); 不執行上一句,則直接從已存在的索引數據中查詢數據。根據不一樣測試輸出內容能夠看出:
不執行重建索引時,會先從全文索引數據中查詢信息,獲取對應主鍵信息,並經過這個主鍵獲取數據庫信息。 當獲取到多個符合條件的數據,採用in('','')的方式查詢數據,若是是單條數據則採用 = 查詢。