Vishal Rajpal

About Vishal Rajpal

Vishal enjoys designing and developing small and mid-sized Enterprise solutions in Java and it's ecosystem. He has graduated from RGTU, India in Electronics and Telecommunication Engineering. Currently, Vishal is working with an Analytics organization, enabling the in-house analytics as well as client teams to use technology as a differentiator for projects / problems related to Big Data.

Eclipse Hibernate Tools plugin Tutorial

In this example, we will learn to install the Hibernate tools plugin for eclipse. Further, we will look at the features available through the plugin, which ease development using hibernate ORM within eclipse.

Hibernate is an object-relational mapping library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database. Hibernate eases object-relational development by replacing direct persistence-related database accesses with high-level object handling functions.

Internally, hibernate maps from Java classes to database tables (and from Java data types to SQL data types). It also provides data query and retrieval facilities by generating SQL calls and relieves the developer from manual result set handling and object conversion.

In this tutorial, the following tools (with versions) have been used:

  1. Eclipse 4.3.2 (Kepler SR2)
  2. JDK 1.7
  3. MySQL 5.6.17
  4. Hibernate 4.3.6

Installing the Hibernate tools Plugin

The Hibernate tools for Eclipse Kepler is available as part of JBoss Tools plugin. The Hibernate tools plugin is available as a separate installation without the other JBoss tools for earlier versions of Eclipse.

Go to Help –> Eclipse Marketplace

  • For version BELOW Eclipse 4.3, search for Hibernate
  • For version ABOVE Eclipse 4.3, search for JBoss

Select the appropriate Hibernate / JBoss tools plugin version based on your Eclipse release. Click Install.

Eclipse MarketPlace - Hibernate Tools Plugin

Eclipse MarketPlace – Hibernate Tools Plugin

On the next page, in case you are installing using the JBoss plugin, please select only the “Hibernate Tools” since the others are specifically related to other general JBoss tools and may take a lot of time to be installed.

Eclipse Plugin - JBoss tools (Hibernate Tools)

Eclipse Plugin – JBoss tools (Hibernate Tools)

Accept the terms before the installation.

Accept Terms and conditions

Accept Terms and conditions

Accept any unsigned content if prompted and re-start eclipse once the installation completes.

Verify the Hibernate Tools plugin

Once the installation completes, you can verify the successful plugin installation.

Browse to Menu –> Window –> Show View. Search for Hibernate. If the installation is successful, you would find the Configurations, Dynamic SQL Preview and Hibernate Query Results View.

Hibernate Tools Plugin - Installation

Hibernate Tools Plugin – Installation

Features of the Hibernate tools plugin

Let us begin with creating a new Java project.
In this tutorial, we have used the maven archetype quick start to create a Java Project. A normal Java project is also good for learning purposes.
Include the hibernate jars as appropriate OR add dependency for hibernate jars for maven.

  1. Wizard & Editor (new hibernate configurations / files)
  2. The plugin provides several wizards which assist in quickly generating hibernate configuration files (database connection properties) and hibernate mapping files (Java to database objects).

    Right click on the project created above, and click New. Search Hibernate and select Hibernate Configuration File (cfg.xml). Enter the desired file name and location for the configuration file. Click Next.

    New Hibernate Configuration File

    New Hibernate Configuration File

    In this page of the wizard, enter the details of the database for the Hibernate Session Factory to create Sessions / connections to. The Database dialect input is a drop down providing various vendors / databases that Hibernate supports. On selecting the dialect, the driver dropdown updates to the respective values of drivers for the database selected in the dialect. This feature helps avoid any typo errors or eases the developer from remembering the options. Enter the jdbc url for the database along with username and password. Click Finish.

    Notice that the Create Console Configuration check-box is checked.

    Hibernate Configuration

    New Hibernate Configuration

    Once the hibernate configuration file is created, you can open it using the Hibernate configuration Editor.

    New Hibernate Configuration

    New Hibernate Configuration

    The hibernate configuration editor segregates the configuration and properties and allows addition / modifications to the same. It allows adding mappings and security contexts.

    Hibernate Configuration Editor

    Hibernate Configuration Editor

  3. Hibernate Console Configuration
  4. A Console configuration describes how the Hibernate plugin should configure Hibernate and what configuration files and classpaths are needed to load the POJO’s, JDBC drivers etc. It is required to make use of query prototyping, reverse engineering and code generation. You can have multiple named console configurations.

    You can create a console configuration by running the Console Configuration Wizard. In this tutorial, the wizard appears directly from step above, since we had enabled the Create Console Configuration option while creating the hibernate configuration file.

    The console configuration lists the Session Factory and also provides the list of tables (database objects) in the database for which the hibernate configuration has been created.

    Hibernate Console Configuration

    Hibernate Console Configuration

    The console configuration can be changed to use a different hibernate version, classpath entries, etc using the Edit Configuration right click menu item. These properties need to be specified if a console configuration is created using the New Wizard (and not through the hibernate config file as we created in the steps above).

    Hibernate Console Configuration

    Hibernate Console Configuration

  5. Mapping Editor
  6. Let us now create a hibernate mapping file to see the features offered by the mapping editor.
    Before we create a mapping, we need the Java Class. We will create an Employee which contains three variables – empId, Name and departmentId.

    Employee.java

    package com.javacodegeeks.training.pojo;
    
    
    public class Employee {
    	private int employeeId;
    	private String employeeName;
    	private int deptId;
    	
    	public Employee() {
    	}
    	
    	public Employee(int employeeId, String employeeName, int deptId) {
    		this.employeeId = employeeId;
    		this.employeeName = employeeName;
    		this.deptId = deptId;
    	}
    	public int getEmployeeId() {
    		return employeeId;
    	}
    	public void setEmployeeId(int employeeId) {
    		this.employeeId = employeeId;
    	}
    	public String getEmployeeName() {
    		return employeeName;
    	}
    	public void setEmployeeName(String employeeName) {
    		this.employeeName = employeeName;
    	}
    	public int getDeptId() {
    		return deptId;
    	}
    	public void setDeptId(int deptId) {
    		this.deptId = deptId;
    	}
    }
    

    Right click on an appropriate package / folder to create a new hibernate mapping file.

    New Mapping File

    New Mapping File

    Select the Employee class created in step above.

    New Mapping File

    New Mapping File

    The wizard helps create the necessary code which can later be changed to provide exact column names if different from the variables in the POJO.

    New Mapping File - Preview

    New Mapping File – Preview

    
    

    The mapping editor offers the numerous code content assists for tags, their attributes, tables, columns and properties within the mapping files.

    Mapping Editor - Content Assist

    Mapping Editor – Content Assist

  7. Console
  8. Once the mapping file is created, let us use the HQL Editor and Hibernate Criteria Editor to create HQL queries using the Eclipse IDE. The plugin provides the query editor to query data using the Session Factory created along with the mappings generated.

    Right click on the Hibernate Configuration, navigate to Mappings tab and add the Employee POJO created in step above.

    Mapping Editor

    Mapping Editor

    Right click on the Employee table and query it using the HQL Editor. Notice the values in the object.

    Mapping Editor

    Mapping Editor

  9. Reverse Engineering
  10. The most powerful feature of Hibernate Tools is a database reverse engineering tool that can generate domain model classes and Hibernate mapping files, annotated EJB3 entity beans, HTML documentation or even an entire JBoss Seam application.

    Go to Menu –> New –> Hibernate –> Hibernate Reverse Engineering File (reveng.xml). Click Next and enter location and name of the xml file.

    Reverse Engineering - Hiberate tools

    Reverse Engineering – Hiberate tools

    In the next step as part of the wizard, select the Hibernate configuration of the database to connect to. Once the Schema objects are visible, select the list of objects / tables for which the model classes and hibernate mapping files need to be generated. Then, click Finish.

    Reverse Engineering - Hibernate tools

    Reverse Engineering – Hibernate tools

    After the file is generated, you still have an option to set filters for objects to be included / excluded while reverse engineering the hibernate code.

    Create a new Launch configuration for Hibernate Code Configurations. Select the Hibernate Console Configuration and the reverse engineering xml file created in steps above.

    Reverse Engineering - Launch configuration

    Reverse Engineering – Launch configuration

    Navigate to Exporters and select the desired files to be generated from the schema.

    Reverse Engineering - Launch configuration

    Reverse Engineering – Launch configuration

    Once the Reverse Engineering launcher configuration is executed, you will notice the hibernate related java and xml files created (highlighted below).

    Reverse Engineering in Action

    Reverse Engineering in Action

  11. Other Features
  12. The plugin also offers features like a Mapping Editor (to view the mappings between java objects to tables) and Hibernate Criteria Editor (to test criterias during development).
    The plugin also includes feature to attach query params to HQL / Criteria queries and view the results in Eclipse.

Hibernate development

Let us go ahead and complete the hibernate code to create a new Employee row in the database and retrieve all the rows from the same table.

The TestHibernate shown below, initializes the SessionFactory for hibernate using the Configuration object. The Configuration uses either the hibernate configuration xml or properties and creates the session factory for hibernate. A hibernate session is then opened using the factory. Transactions are then created using the hibernate sessions to persist objects to database AND also access the database rows. This is done within the TestHibernate through two methods – addEmployee and getAllEmployees which help create a new employee row in the database table and retrieve all rows from the table, respectively.

TestHibernate.java

package com.javacodegeeks.traning.HibernateToolsPlugin;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
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.service.ServiceRegistry;

import com.javacodegeeks.training.pojo.Employee;

public class TestHibernate {
	private static SessionFactory factory;
	private static ServiceRegistry serviceRegistry;

	public static void main(String[] args) {
		Configuration configuration = new Configuration();
		configuration.configure();
		configuration.addAnnotatedClass(Employee.class);
		serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
				configuration.getProperties()).build();
		
		factory = configuration.buildSessionFactory(serviceRegistry);
		TestHibernate testWorker = new TestHibernate();
		testWorker.addEmployee(3, "JavaCodeGeeks", 401);
		
		List allEmployees = testWorker.getAllEmployees();
		for(Employee emp : allEmployees){
			System.out.print(emp.getEmployeeId() + "  ");
			System.out.print(emp.getEmployeeName() + "  ");
			System.out.print(emp.getDeptId() + "  ");
                        System.out.println();
		}
		
	}

	private int addEmployee(int empId, String empName, int deptId) {
		Session session = factory.openSession();
		Transaction tx = null;
		Integer empIdSaved = null;
		try {
			tx = session.beginTransaction();
			Employee emp = new Employee(empId, empName, deptId);
			empIdSaved = (Integer) session.save(emp);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return empIdSaved;
	}
	
	@SuppressWarnings("unchecked")
	private List  getAllEmployees(){
		Session session = factory.openSession();
		Transaction tx = null;
		List employees = new ArrayList();
		try {
			tx = session.beginTransaction();
			employees = (List)session.createQuery("FROM Employee").list(); 
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return employees;
	}
}

Before executing the program, confirm the number of rows in the table:

mysql> select * from employee;
+--------+----------+---------+
| emp_id | emp_name | dept_id |
+--------+----------+---------+
|      1 | Vishal   |     100 |
|      2 | Rajpal   |     202 |
+--------+----------+---------+
2 rows in set (0.00 sec)

Execute the program, and the below output is seen:
The hibernate initialization and mapping logs have been ignored.

1  Vishal  100  
2  Rajpal  202  
3  JavaCodeGeeks  401  

Re-run the query in the database, and verify the new row created:

mysql> select * from employee;
+--------+---------------+---------+
| emp_id | emp_name      | dept_id |
+--------+---------------+---------+
|      1 | Vishal        |     100 |
|      2 | Rajpal        |     202 |
|      3 | JavaCodeGeeks |     401 |
+--------+---------------+---------+
3 rows in set (0.00 sec)

Download the Eclipse Project

This was an example demonstrating use of Hibernate tools plugin in eclipse.

Download
You can download the full source code of this example here : HibernateToolsPlugin.zip

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close