facebook

Hibernate Development

Become familiar with this open-source JORM, which is very easy to use and offers a variety of features.  Here you will learn to:

  • Configure a hibernate project
  • Reverse engineer a database table
  • Use two editors

This feature is available in MyEclipse.

1. What is Hibernate?

Hibernate is a very popular open-source, Java-based object-relational mapping (JORM) engine that is easy to get up and running. It provides a rich set of features including:

  • Multiple mapping strategies
  • Transitive persistence
  • Single object to multiple table mapping
  • Collections support
  • Polymorphic associations
  • Customizable SQL queries

Hibernate is used to map database structures to Java objects at runtime. Using a persistence framework like Hibernate allows developers to focus on writing business logic instead of writing an accurate and performant persistence layer (which includes, DAOs, SQL queries, JDBC code, connection management, etc.).

Hibernate can be used by any Java application that requires moving data between Java application objects and database tables. Thus, it’s very useful in developing two and three-tier Java EE applications. Integration of Hibernate into your application involves:

  • Installing the Hibernate core and support JAR libraries into your project
  • Creating a hibernate.cfg.xml file to describe how to access your database
  • Creating individual mapping descriptor files for each persistable Java classes

1.1 Some History Leading Up to Hibernate

In the early years of Java database and web programming, developers accessed their databases using the different classes provided by the java.sql package. This consisted of getting a driver from the DriverManager, creating and using a connection, handling exceptions properly, closing the connection and so on. A common problem at this stage was forgetting to clean up database connections and getting connection exceptions in your applications after they had been running for a while.

A few years later, connection pools became a big topic because they allowed developers to stop worrying about creating and managing (cleaning up) DB connections and instead focusing on their SQL and ResultSet parsing code. Suddenly, the problem of connection exceptions to the database in long-running applications had been mostly solved. However, it was still common to see hundreds of lines of boiler-plate code used to populate queries with values and parse the ResultSets returned from SQL queries.

A few more years went by and someone had an idea to automatically map ResultSet results directly to Java objects, which mostly solved the problem of all the redundant boiler-plate parsing code. At that point, Java database development had taken several big steps forward and was getting much simpler. Then, Hibernate came into the picture.

With Hibernate came the idea that not only these things continue to be automated, but Hibernate would also manage the state of your objects in memory and it would worry about when and how object values would be read from or written to the database. Now, developers were dealing only with objects (or mapped objects) and letting Hibernate handle everything else. Developers were no longer writing JDBC and SQL code. Instead, they were using code that did that work for them.

At the time Hibernate came on the scene, the other persistence technology available was EJB 2.x. Hibernate’s timing, ease of use and power, all contributed to one of the fastest uptakes of a technology that the Java space had seen in quite awhile.

2. Hibernate Project Configuration

You can create a hibernate-enabled project by creating any of the supported types of base projects, like a Java or Web project, and then adding  the Hibernate facet. MyEclipse creates a hibernate.cfg.xml file for you, and you must specify database connection details.

You can also add multiple facets to a project simultaneously by opening the Project Facets property of the project.


Adding facet via project properties

2.1 Hibernate Mapping and Configuration

Hibernate is written in Java and is highly configurable through two types of configuration files. The first type of configuration file is named hibernate.cfg.xml. On startup, Hibernate consults this XML file for its operating properties, such as database connection string and password, database dialect, and mapping files locations. Hibernate searches for this file on the classpath.


Project with Hibernate capabilities and the Hibernate configuration file

The second type of configuration file is a mapping description (file extension *.hbm) that instructs Hibernate how to map data between a specific Java class and one or more database tables. MyEclipse provides tools for working with each of these configuration file types and keeping them in-sync as you make database and Hibernate-mapped Java class changes. The editor has the following features:

  • Advanced form-based editor and accompanying wizards.
  • Hyperlink navigation to referenced classes and properties.
  • Class name auto completion.
  • Property name auto completion.
  • Content assist for mapping file elements, attributes, and values. 


HibernateMapping Editor – Design page


Adding meta element


Hibernate Mapping Editor – Source page

3. Reverse Engineering a Database Table

You can reverse-engineer database table information into Hibernate (Java) objects,  and add them to a project. For maximum control over your generated Hibernate objects, you can select details in the wizard like primary key generation strategy, object names, types and more.

In the Database Explorer perspective, you can view the contents of the database to which you are connected. From the DB Browser, right-click the table you want to reverse engineer, and select Hibernate Reverse Engineering from the menu. After you complete the wizard, you are prompted to switch to the Hibernate perspective.


Reverse engineering a table

The classes are generated into the Java package you select in the wizard.


Generated classes

When you reverse-engineer database tables, the entities appear in the Mappings section of the configuration file.

4. HQL Editor

The HQL Editor, and other HQL views in the Hibernate perspective, assist in the development, evaluation or testing of HQL queries. HQL is a SQL-like language called Hibernate Query Language. It can sometimes look like simplified SQL and uses object names and references instead of table and column names. A great place to learn about HQL is the Hibernate Reference Document. This editor has the following features:

  • Content Assist
  • Hibernate Dynamic Query Translator view translates HQL queries into SQL as you type
  • Hibernate Query Results view can contain multiple result sets; result properties are displayed in the Properties view
  • Query Parameters view allowing easy execution of variable queries
  • Project selector allowing you to switch context between different Hibernate projects

With the HQL Editor, you can write HQL on the fly, and run it. The editor, utilizing the objects that MyEclipse reverse-engineered from the database, translates the query to SQL (shown in the bottom right), and then runs it. The result is returned in Java objects and is shown in the bottom left corner.


HQL query translated to SQL

After you reverse-engineer a database, you are ready to start writing your application to read, write, and update objects in your database. When you have your Java classes and methods in place, you can run a Hibernate query in the HQL editor to query the database. This is an alternate method of querying the database; you can also switch to the Database Explorer perspective and query the database from there to see the same results.

5. Criteria Editor

In addition to the HQL editor, the MyEclipse Hibernate tools also include a Criteria editor. Criteria in Hibernate is a way to utilize instances of objects, combined with query constraints, to create queries against your entities. For example, say you create an entity instance with a type of User. Specifying that entity as a criteria for your query and telling the Criteria to return only the first 10 results is an effective and fast way to create a complex query to use for your entities.

To access the Criteria editor, right-click a project containing the Hibernate facet, and select MyEclipse>Open Criteria Editor.


Opening the Criteria editor

After the Criteria editor is open, you can type any valid Java code that represents criteria into the editor and execute them using the Run icon at the top of the editor.

The example below shows a simple criteria based on an `EchoMessage` entity, asking Hibernate to return the `EchoMessage` entity having an Id value of 2. The result appears in the Result view.


Executing a Criteria query

Any valid criteria-based code can be written and executed using the Criteria editor in MyEclipse. When typing a criteria in the Java editor, selecting it and invoking quick fix displays a Copy to Criteria editor action. Selecting this action opens the Criteria editor, initialized with the selected text.


Copy to Criteria editor action

You can test and edit the criteria in the Criteria editor. When done, closing the editor allows you replace the originally selected text with the modified criteria query.

6. FAQ

How does Hibernate compare to EJB 3 / JPA?
Hibernate 3.2 is actually JPA-compatible, implementing all the new annotations that make JPA so automatic and painless to use. So instead of using a commercial implementation of JPA, you can use Hibernate and still keep all the standard JPA annotations in your classes without any changes.

Can Hibernate scale to very large applications?
Yes. Actually the roots of Hibernate come from the two founders own experiences working as consultants on large enterprise applications. Hibernate is their vision of how persistence should function in an application. Also a few years ago, Gavin King, put out a challenge to the community to find hand-tweaked JDBC SQL that executed a magnitude faster than the generated SQL from Hibernate to make a point that the framework is very focused on being functional, flexible and performant.

MyEclipse FAQ
Support Forum FAQ