To make the learning easier, I have used SQLite database which is a self-contained, serverless, zero-configuration, transactional SQL database engine. But you are free to choose any other database as well to learn this tutorial. To run example shown in this tutorial, you do not have to install any database or SQLite database seperately. However to browse the database you can use 'SQLite Manager - Firefox addon' which provides a very nice GUI for SQLite database.

Tools and Technologies used in this article :

  1. Hibernate Search 4.1

  2. Maven

  3. SQLite 3 database

  4. SQLite Manager - Firefox addon

  5. Eclipse 3.7

1. Create a Java Project using Maven Tool

In the command prompt execute the following command to generate Maven compatible Java project named as 'HibernateSearchHelloWorld'.

	mvn archetype:generate -DgroupId=com.srccodes.example.hibernate -DartifactId=HibernateSearchHelloWorld -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
Generated Maven Java Project structure
Maven Java Project structure

 

2. Update pom.xml

Add dependency of Hibernate core and SQLite jdbc library. Also update 'maven-compiler-plugin' so that it uses compilation level 1.5 onwards. Otherwise annotation (introduced in JDK 5) will not work.

File : pom.xml

 

3. Convert to Eclipse compatible Java project

Open the directory 'HibernateSearchHelloWorld' in command prompt and run the following maven command.

	mvn eclipse:eclipse
Screenshot of command prompt
Maven Java Project

On completion of the above command, Maven Java project will be converted to a Eclipse compatible java project.

Eclipse compatible Java Project structure
Eclipse Java Project

 

4. Import project in Eclipse

Open Eclipse IDE and select from the menu File --> Import --> General --> Existing Projects into Workspace

Existing Projects into Workspace

Browse to the directory of the newly converted Eclipse compatible Java Project and click 'Finish' button.

Browse project
Screenshot of Eclipse project structure
Eclipse project structure

 

5. Add Hibernate Configuration file

Right click on 'main' and select from context menu 'New' --> 'Folder'.

new folder

Enter 'resources' in the 'Folder name' field and click the 'Finish' button.

resources folder

Copy the 'hibernate.cfg.xml' file in the 'resources' folder.

File: hibernate.cfg.xml
Note :
'mydb.db' is the SQLite database file included with the sourcecode attached in 'Download Source Code' section. You can create db file of your own using 'SQLite Manager - Firefox addon' UI. But copy that file inside 'HibernateSearchHelloWorld' project directory directly.

I have set the property 'hibernate.hbm2ddl.auto' to 'update' so that when you will execute the code it will create the database tables of it's own based on the entity class 'com.srccodes.example.hibernate.Contact') we have written and referenced in this configuration file.

Set property 'hibernate.search.default.indexBase' to a writeable directory where Lucene will create index for your domain objects.

 

6. Configure Java Build Path

Right click on 'HibernateSearchHelloWorld' project and select from context menu 'Properties' --> 'Java Build Path'.
Add 'resources' folder as shown in the screenshot below

Java Build Path

 

7. Add SQLiteDialect

Copy from attached source code or download SQLiteDialect and add under package 'org.hibernate.dialect' in your project.

Note :
dialect is used to help hibernate framework to create underlying database specific SQL query.

 

8. Write Entity class

Create a class 'Contact' under the package 'com.srccodes.example.hibernate' and copy the following content.

File: Contact.java
package com.srccodes.example.hibernate;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.Store;

/**
 * The persistent class for the contact database table.
 * 
 */
@Entity
@Indexed
@Table(name = "contact")
public class Contact {
	private Integer id;
	private String name;
	private String email;

	public Contact() {

	}

	public Contact(Integer id, String name, String email) {
		this.id = id;
		this.name = name;
		this.email = email;
	}

	@Id
	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	@Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO)
	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
	
	@Override
	public String toString() {
		StringBuilder stringBuilder = new StringBuilder("Id: ").append(this.getId()).append(" | Name:").append(this.getName()).append(" | Email:").append(this.getEmail());
		
		return stringBuilder.toString();
	}
}
Note :

To know basic hibernate annotation follow the tutorial Hibernate Hello World example using Maven build tool and SQLite database

@Indexed annotation specifies an entity as indexable.
@Field annotation specifies an field as searchable. Here Index.YES means 'name' field will indexed, Analyze.YES means that filed will be analyzed (excludes common stop words like 'a', 'an', 'and', 'the' etc) using default Lucene Analyzer, Store.NO means actual 'name' field data will not be stored in the index.

I have also written 'toString()' method which we'll use to print out domain objects in console.

 

9. Common utility class for Hibernate

Copy the following code to 'HibernateUtil' class of package 'com.srccodes.example.hibernate'.

File: HibernateUtil.java
package com.srccodes.example.hibernate;

import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * Contains utility methods 
 * 
 * @author srccodes.com
 * @version 1.0
 *
 */
public class HibernateUtil {
	
	private static SessionFactory sessionFactory = null;  
	private static ServiceRegistry serviceRegistry = null;  
	  
	private static SessionFactory configureSessionFactory() throws HibernateException {  
	    Configuration configuration = new Configuration();  
	    configuration.configure();  
	    
	    Properties properties = configuration.getProperties();
	    
		serviceRegistry = new ServiceRegistryBuilder().applySettings(properties).buildServiceRegistry();          
	    sessionFactory = configuration.buildSessionFactory(serviceRegistry);  
	    
	    return sessionFactory;  
	}
	
	// We need to configure session factory once. 
	// Rest of the time we will get session using the same.
	static {
		configureSessionFactory();
	}
	
	private HibernateUtil() {}
	
	public static Session getSession() {
		return sessionFactory.openSession();
	}
}
Note :
'configureSessionFactory()' method will build the hibernate session factory based on the configuration in 'hibernet.cfg.xml' file.

'getSession()' method will provide a Hibernate session from the configured session factory.

 

10. Hibernate Search and Indexing code

Copy the following code to 'App' class of package 'com.srccodes.example.hibernate'.

File: App.java
Note :
'doIndex()' method will generate indexes for your domain objects in the directory specified in the 'hibernate.search.default.indexBase' property in 'hibernate.cfg.xml' file.

'search(String queryString)' method will prepare a Lucene search query based on the query string. Then that query will be wrapped in a javax.persistence.Query which will be executed to return matching domain objects.

 

11. Final project structure

After doing all the changes the overall project structure will look like this

overall project structure

 

12. Populate 'Contact' table with data

Browse the 'mydb.db' SQLite database file (under 'HibernateSearchHelloWorld' project) using 'SQLite Manager - Firefox addon'. Populate the 'Contact' table with some dummy test data.

Screenshot of the table using 'SQLite Manager - Firefox addon' UI
SQLite Manager

 

13. Run Your Code

Right click on 'App.java' and select from context menu 'Run As' --> 'Java Application'.

 

13. Console Output

In the console, all the records of the 'Contact' table will be printed first. Then you will be prompted to enter search key. Based on the search key Hibernate Search API will return all the matching domain objects which will be printed in the console. To exit from the command prompt you have to type 'X'.

Console

 

Download Source Code

 

References