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:
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. The second type of configuration file is a mapping description file (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.
Hibernate may 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 J2EE applications. Integration of Hibernate into your application involves:
To learn more about Hibernate's basic and advanced features, or how to develop with Hibernate, see the Resources section below.
Back to Top
This section describes the process for creating a simple Java application named HibernateDemo that uses Hibernate to persist text messages to a single database table. Because the majority of corporate web projects involve interacting with existing corporate data in a relational database, we will concentrate on forward-engineering Java data objects and mapping descriptors from an existing database.
The database table description that we will map to a Java class is listed below. We have also added a couple of records to the table to facilitate testing.
echo_message DDL |
CREATE TABLE echo_message |
Typically before you begin Hibernate development you need a working Database Explorer Connection Profile. For this tutorial, we use the Oracle database connection profile that we created in Database Explorer Quickstart tutorial.
Note: Even though this Quickstart uses Oracle, the instructions and the sample table above are generic enough to work with any database.
Back to Top
We begin by creating a basic Java project named HibernateDemo that reads and writes data to and from the echo_message database table.
Back to Top
Once the HibernateDemo project has been created, we will now add MyEclipse Hibernate capabilities to it. This wizard-based process performs the following actions:
We begin by opening the MyEclipse Add Hibernate Capabilities wizard:
Table-1. Hibernate Support Wizard - Page1 options
Field Description Hibernate Specification
Hibernate version for which support is added to the project. To leverage the most out of MyEclipse Hibernate Tooling, Hibernate 3.1 is recommended.
MyEclipse/User Libraries
A list of library sets which can be added to your project's build-path.
Add checked Libraries to project build-path
Checked libraries will be added to your project's build-path, but the corresponding JAR files will not be copied into your project. The JAR files will be copied on deployment and this is the recommended setting.
Copy checked Library Jars to project folder and add to build-path
Checked library JARs will be copied into your project and added to its build-path.
Library Folder
Only applicable if the above option is chosen.
A project relative path to a new or existing folder that Hibernate libraries will be copied into by the wizard.
Figure 4. Hibernate Configuration File Setup
Figure 5. Hibernate Datasource Configuration
The Datasource configuration performed above may be skipped now and carried out later using the Hibernate Configuration editor.
The final step in configuring the project properly is to create a SessionFactory class that will be used to access Hibernate's capabilities from within the codebase. A screenshot of this wizard page is shown in Figure 6.
Figure 6. Create SessionFactory details
Table 3 - Hibernate Support Wizard - Page3 Options
Field | Description |
Create SessionFactory Class |
If enabled, the wizard will create a new class that will provide Hibernate session factory class. |
Java source folder |
Determines the source folder in which the new class will be created. |
Java package |
Specifies the package in which the Session Factory will be created. |
Class name |
Specifies the name of the Session Factory class. |
Java Compliance Level |
Java compliance level of the generated Session Factory. |
The wizard completion process performs the following actions:
- Installs the Hibernate libraries (JARs) to the project if you chose to copy the libraries into your project on page 1
- Updates the project's build-path to include the installed Hibernate libraries
- Creates and configures the hibernate.cfg.xml file for the project
- Creates a custom SessionFactory class (e.g., HibernateSessionFactory) for your project that simplifies Hibernate session handling
Figure 7 highlights the important features of the newly created HibernateSessionFactory.java file. This class manages a single Hibernate Session object that is lazily initialized by the getSession() method and is flushed and released by the closeSession() method. At runtime, the Hibernate session creation process must be able to locate the hibernate.cfg.xml file on the classpath. The CONFIG_FILE_LOCATION variable defines the package-relative path to the hibernate.cfg.xml file. The default value is provided by the Hibernate Support Wizard. If you relocate the hibernate.cfg.xml file, you must manually revise the CONFIG_FILE_LOCATION value to reference the new location or you may use the setConfigFile() method to set it before use.
Figure 7. HibernateSessionFactory class
Back to Top
After finishing the wizard in section 5.2, the hibernate configuration file will be automatically opened.
If you skipped the datasource configuration while adding capabilities, you will need to do it now, else move ahead to adding properties.
Customizing the configuration file with the information it needs to connect to our database.
Figure 8. Hibernate Configuration file with Oracle connectivity configured
Figure 9. Adding properties
Figure 11 shows the hibernate configuration file source after the above steps have been completed.
Figure 10. Adding mapping files
Figure 11. Hibernate Configuration File
This section presents a process that uses the MyEclipse Hibernate tools to forward engineer Java data objects and mapping definitions from existing database tables.
Field | Description |
Java src folder |
The project and the source folder into which the mapping files, POJOs and DAOs will be generated. |
Java package |
The package into which the mapping files, POJOs and DAOs will be generated. |
Hibernate mapping file |
Generate mapping files from the selected tables. |
Update hibernate configuration |
Add the mapping files generated to your hibernate configuration file. |
Java Data Object |
Generate data objects (POJOs) corresponding to your mapping files and tables. |
Create abstract class |
Generate an abstract superclass for each data object. The abstract classes will be overwritten in subsequent generation passes, but the corresponding subclass will not be overwritten. |
Base persistence class |
The fully qualified name of a class which the generated POJOs should extend if required. |
Java Data Access Object |
Generate data access object for convenient access to the mapped classes and tables. Users may choose between Basic, Spring and JNDI DAOs. |
Generate precise findBy methods |
Generate a "findBy" method for each property in the mapped class. |
Use custom templates |
Override MyEclipse's internal velocity templates with your own versions. |
Template directory |
Directory containing the root of the custom template tree. |
Figure 14. Hibernate Reverse Engineering Wizard - Page 2
Field | Description |
Rev-eng settings file |
This file contains the reverse engineering configuration and preferences and retains them for future use. Use the Setup... button to supply an existing file or create a new one. |
Type Mapping |
Determines whether Java or Hibernate types will used in the type property of field mappings, e.g. java.lang.String vs. string. This setting will only be used if a more specific setting in the Customized Type Mappings list or page 3 of this wizard cannot be found. |
ID Generator |
The ID Generator is a required filed in the Hibernate mapping file. It defines the Java class used to generate unique identifiers for instances of the persistent class. See the Resources section for a link to the Hibernate documentation that describes each of these ID Generator values in detail. |
Generate basic typed composite IDs |
If a table has a multi-column primary key, a |
Generate version and timestamp tags |
If enabled, columns named "version" and "timestamp" are represented as |
Customized Type Mappings |
Allows you to specify a custom mapping from a JDBC type to a Hibernate type, using Length, Scale, Precision and Nullability as qualifying criteria for the JDBC type. |
Field | Description |
Class name |
The fully qualified name of the data object class corresponding to this table. |
ID Generator |
The ID generator you wish to use for this table. |
JDBC type |
The JDBC type override for this column. |
Property name |
The name of the generated property corresponding to this column. |
Hibernate type |
The Hibernate type corresponding to this column. |
Include referenced / referencing tables |
Expands the set of tables to be reverse engineered to other tables referenced by this table and tables referencing this table respectively. |
Generate support for ListedTable(fk)->UnlistedTable and UnlistedTable(fk)->ListedTable |
Generate code corresponding to the relationships this table has with other tables which are not being currently reverse engineered and are absent from the table list on this page. |
The wizard completion process performs the following actions:
Figure 15 highlights the classes, key methods and mapping file generated as well as the reference to the mapping file added in the hibernate.cfg.xml file.
Figure 15. Updated project following Hibernate Mapping Wizard execution
MyEclipse includes a customized XML editor for editing Hibernate mapping files (*.hbm.xml). This editor is automatically opened when you double click a mapping file. You can also right click the file and choose Open With > MyEclipse Hibernate Mapping Editor.
Features
Back to Top
MyEclipse includes a Hibernate Query Language editor and several views that allow you to execute HQL queries against your Hibernate configuration.
Features
Figure 17. Opening the HQL editor
Figure 18. Executing a query in the HQL editor
Figure 19. Query Parameters view
Back to Top
Once the Hibernate persistence has been integrated into the HibernateDemo project, the next step is to test it. One method for testing Hibernate persistence is to create a Java class with a main method. The testing class will use the Java object and HibernateSessionFactory created by the Hibernate wizards. Look at the two important methods defined on the HibernateSession class as shown in Figure 18 that will be used in the test code.
|
Shown are two important static methods in the SessionManager class. getSession(): This method will return a Session variable that can been used to access the Hibernate Session class. Anytime you want to use the Hibernate session you can call this method to obtain the cached Hibernate Session. closeSession(): If a session has been started it simply closes it. |
Following is a list of the steps in the test code along with a sample of the source code
HibernateReadTest.java |
package com.genuitec.hibernate; |
Back to Top
Back to Top
This concludes your introduction to Hibernate Development using MyEclipse. Additional Quickstart documents are available that introduce working with the Database Explorer, Struts, JSF, Web Projects, editing, application server configuration, EJB development, and enterprise application projects. For more information visit the MyEclipse Quickstart library .