... <property name="hibernate.search.default.directory_provider" value="filesystem"/> <property name="hibernate.search.default.indexBase" value="D:\dojupload\index> ...First you have to tell Hibernate Search which DirectoryProvider to use. This can be achieved by setting the hibernate.search.default.directory_provider property. Apache Lucene has the notion of a Directory to store the index files. Hibernate Search handles the initialization and configuration of a Lucene Directory instance via a DirectoryProvider. In this tutorial we will use a a directory provider storing the index in the file system. This will give us the ability to physically inspect the Lucene indexes created by Hibernate Search.
<?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"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/test</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <property name="hibernate.search.default.directory_provider">filesystem</property> <property name="hibernate.search.default.indexBase">D:\dojupload\index</property> <!-- Mapping files --> <mapping class="com.dineshonjava.h4java.Book"/> </session-factory> </hibernate-configuration>Now next to the directory provider you also have to specify the default base directory for all indexes via hibernate.search.default.indexBase. Lets assume that your application contains the Hibernate managed classes com.dineshonjava.h4java.Book and you want to add free text search capabilities to your application in order to search the books contained in your database.
package com.dineshonjava.h4java; ... @Entity public class Book { @Id @GeneratedValue private Integer id; @Column private String title; @Column private String subtitle; @Column private Date publicationDate; public Book() {} public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSubtitle() { return subtitle; } public void setSubtitle(String subtitle) { this.subtitle = subtitle; } public Date getPublicationDate() { return publicationDate; } public void setPublicationDate(Date publicationDate) { this.publicationDate = publicationDate; } }@Indexed-
package com.dineshonjava.h4java; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.apache.solr.analysis.LowerCaseFilterFactory; import org.apache.solr.analysis.SnowballPorterFilterFactory; import org.apache.solr.analysis.StandardTokenizerFactory; import org.hibernate.search.annotations.Analyze; import org.hibernate.search.annotations.AnalyzerDef; import org.hibernate.search.annotations.DateBridge; import org.hibernate.search.annotations.Field; import org.hibernate.search.annotations.Index; import org.hibernate.search.annotations.Indexed; import org.hibernate.search.annotations.Parameter; import org.hibernate.search.annotations.Resolution; import org.hibernate.search.annotations.Store; import org.hibernate.search.annotations.TokenFilterDef; import org.hibernate.search.annotations.TokenizerDef; @Entity @Indexed public class Book { @Id @GeneratedValue private Integer id; @Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO) private String title; @Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO) private String subtitle; @Field(index = Index.YES, analyze = Analyze.NO, store = Store.YES) @DateBridge(resolution = Resolution.DAY) private Date publicationDate; public Book() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSubtitle() { return subtitle; } public void setSubtitle(String subtitle) { this.subtitle = subtitle; } public Date getPublicationDate() { return publicationDate; } public void setPublicationDate(Date publicationDate) { this.publicationDate = publicationDate; } @Override public String toString() { return "Book [id=" + id + ", title=" + title + ", subtitle=" + subtitle + ", publicationDate=" + publicationDate + "]"; } }
FullTextSession fullTextSession = Search.getFullTextSession(session); fullTextSession.createIndexer().startAndWait();After executing the above code, you should be able to see a Lucene index under "D:\dojupload\index\com.dineshonjava.h4java.Book"
package com.dineshonjava.h4java; import java.util.Date; import java.util.Iterator; import java.util.List; import org.hibernate.Transaction; import org.hibernate.search.FullTextSession; import org.hibernate.search.query.dsl.QueryBuilder; public class App { public static void main(String[] args) { org.hibernate.Session session=HibernateSessionFactory.getSession(); try{ Book book=new Book(); book.setPublicationDate(new Date()); book.setSubtitle("jsp"); book.setTitle("tech"); //session.saveOrUpdate(book); FullTextSession fullTextSession = org.hibernate.search.Search.getFullTextSession(session); Transaction tx = fullTextSession.beginTransaction(); QueryBuilder qb = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity( Book.class ).get(); org.apache.lucene.search.Query query = qb.keyword().onFields("title", "subtitle").matching("jsp").createQuery(); // wrap Lucene query in a org.hibernate.Query org.hibernate.Query hibQuery = fullTextSession.createFullTextQuery(query, Book.class); // execute search List result = hibQuery.list(); Iterator<Book> it = result.iterator(); while (it.hasNext()) { Book book1 = (Book) it.next(); System.out.println(book1); } tx.commit(); } catch (Exception e) { // TODO: handle exception }finally{ session.close(); } } }
package com.dineshonjava.h4java; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; /** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html }. */ public class HibernateSessionFactory { /** * Location of hibernate.cfg.xml file. * Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file. * The default classpath location of the hibernate config file is * in the default package. Use #setConfigFile() to update * the location of the configuration file for the current session. */ private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static Configuration configuration = new Configuration(); private static org.hibernate.SessionFactory sessionFactory; private static String configFile = CONFIG_FILE_LOCATION; static { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } private HibernateSessionFactory() { } /** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */ public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; } /** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } /** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /** * return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /** * return session factory * * session factory will be rebuilded in the next call */ public static void setConfigFile(String configFile) { HibernateSessionFactory.configFile = configFile; sessionFactory = null; } /** * return hibernate configuration * */ public static Configuration getConfiguration() { return configuration; } }
Labels: hibernate4