You are on page 1of 21

MyEclipse Hibernate Quickstart

Last Revision: January 24, 2006

Outline
1. Preface
2. Requirements
3. Introduction
4. Hibernate Overview
5. Creating the HibernateDemo Project
1. Create the HibernateDemo Java Project
2. Add Hibernate Capabilities
3. Customizing the Hibernate Configuration File
4. Create Hibernate Java Table Mapping
6. Testing the HibernateDemo Application
7. Summary
8. User Feedback
9. Resources

1. Preface
This document was written using Sun JDK 1.4.2, Eclipse 3.1 and MyEclipse 4.0. All screenshots are based upon the
default user interface settings for Eclipse, MyEclipse Enterprise Workbench, and Windows XP. If you experience
difficulty with the instruction of this document, please see the User Feedback section for how to provide feedback to the
MyEclipse documentation team.

Back to Top

2. Requirements
Below is a list of requirements for this Quickstart:

1. Java 2 SDK, Standard Edition 1.4 or later installed (see Resources for a download link)
2. Eclipse 3.1 SDK (see Resources for a download link)
3. MyEclipse 4.1 (see Resources for a download link)
4. A database server that is supported by Hibernate and the MyEclipse Database Explorer such as:

• Axion • Mimer SQL


• Hypersonic DB • MySQL
• InstantDB • Oracle
• Interclient • Pointbase
• Firebird • PostgresQL
• ODBC Bridge • SAPDB
• jTDS • Sunopsis XML
• Mckoi • Sybase
• Microsoft SQL Server • ThinkSQL

Back to Top

3. Introduction
This quickstart presents the basic features, concepts, and techniques for getting started with Hibernate
development using MyEclipse Enterprise Workbench. We do this while walking you through the development process
of a very simple Java Hibernate application. For questions and concepts not fully covered in this tutorial, we refer you
to the Resources section for a list of Hibernate resources.

Specifically this document presents how to:

• Add MyEclipse Hibernate support to a Java project


• Create a Hibernate configuration file for your project
• How to use a custom SessionFactory
• Generate Java classes and Hibernate database mapping (.hbm) files from Database Explorer table definitions
• Create a small test application that uses Hibernate

Note: Completion of the Database Explorer Quickstart tutorial is a prerequisite to this quickstart as MyEclipse
Hibernate tools take advantage of Database Explorer connection and meta-data capabilities.

Back to Top

4. Hibernate Overview
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 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:

• 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
To learn more about Hibernate's basic and advanced features, or how to develop with Hibernate, see the Resources
section below.

Back to Top

5. Creating the HibernateDemo Project


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.

echo_message DDL

CREATE TABLE echo_message


(
id INT(11) PRIMARY KEY not null,
msg VARCHAR(255)
)

Typically before you begin Hibernate development you need a working Database Explorer Connection Profile. For this
tutorial, we use the MySQL database connection profile that we created in Database Explorer Quickstart tutorial (see
Resources ).

Back to Top

5.1 Creating the HibernateDemo Java Project

We begin by creating a basic Java project named HibernateDemo that reads and writes data to and from the
echo_message database table.

1. From the MyEclipse menubar select File > New > Project > Java Project. This will launch the New Java
Project wizard.
2. Enter HibernateDemo for the Project name
3. Select the Create separate source and output folders option for Project Layout.
4. Select Finish to complete the page, as shown in Figure 1

Note: Upon completion of the wizard you will be asked if you wish to switch to the Java Perspective. Choose
no to remain in the MyEclipse Perspective. If you are not in the MyEclipse perspective, then switch now by
selecting Window > Open Perspective > Other... > MyEclipse.
Figure 1. New HibernateDemo Project

Back to Top

5.2 Adding Hibernate Capabilities to HibernateDemo Project

Once the HibernateDemo project has been created, we will now add MyEclipse Hibernate capabilities to it. This wizard-
based process performs the following actions:

• Copies the Hibernate libraries (JARs) to the project


• Adds the Hibernate libraries to the project's classpath
• Creates and configures the hibernate.cfg.xml for the project
• Creates a custom SessionFactory class for your project that simplifies Hibernate session handling

We begin by opening the MyEclipse Add Hibernate Capabilities wizard:

1. From the Package Explorer select the HibernateDemo project


2. Next, from MyEclipse menubar select MyEclipse > Add Hibernate Capabilities ... to launch the wizard (see
Figure 2).
Figure 2. Launching the "Hibernate Support" Wizard

Figure 3. Adding Hibernate Support to Java Project

3. Select Add Hibernate libraries to project.


4. Enter /lib for Library folder. If your project organizes its libraries differently, select browse to choose
another project directory.
5. Select Append Hibernate libraries to project classpath
6. Select New for the Hibernate config file field.
7. Complete the page as shown in Figure 3, and then select Next.

Table-1. Hibernate Support Wizard - Page1 options

Field Description
The name of the project to which the Hibernate capabilities will be added.
Project Name
Use the Browse button to select a different Java project.

Add Hibernate Instructs the wizard to copy all Hibernate libraries (Jars) to the project relative
Library Support folder specified in the Library Folder field

A project relative path to a new or existing folder that Hibernate libraries will
Library Folder
be copied into by the wizard.

Append Hibernate If enabled, this preference directs the wizard to add each Hibernate library
libraries to project copied into the project to the project's build path. Doing this allows MyEclipse
classpath and Eclipse Java tools to work on Hibernate-based files without error.

Select New if you wish for the wizard to create a new hibernate.cfg.xml file;
Hibernate Config File otherwise select Use Existing. To select an existing hibernate.cfg.xml file use
the Browse button to see the project's contents.

The path to an existing hibernate.cfg.xml file that will be used rather than
Existing Config File
create a new config file.

If you chose to create a new hibernate configuration file in the previous step, you will be presented with a dialog (see
Figure 4) allowing you to customize the name and location of the configuration file.

Figure 4. Hibernate Configuration File Setup

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 5.
Figure 5. Create SessionFactory details

Table 3 - Hibernate Support Wizard - Page3 Options

Field Description

Create SessionFactory If enabled, the wizard will create a new class that will provide Hibernate
Class session factory class.

Specifies the name of the SessionFactory class. Select the Packages...


SessionFactory Class
button to browse for the package location.

Source Folder Determines the source folder to add the new SessionFactory class.

1. Select Create SessionFactory class


2. Enter a fully qualified classname for the Session Factory Class. You can optionally browse for the package
using Packages...
3. Choose the Source Folder that will contain the Hibernate session class. The drop-down list will display all
available source folders within the project.
4. Complete the page as shown in Figure 5, and then select Finish.

Note: During the completion process, the wizard may appear inactive for up to 30 seconds as it copies libraries
and updates various project resources. Please be patient and wait for it to complete before taking any further
actions.

The wizard completion process performs the following actions:

• Installs the Hibernate libraries (JARs) to the project


• 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., SessionManager) for your project that simplifies
Hibernate session handling

Figure 6 highlights the important features of the newly created SessionManager.java file. This class
manages a single Hibernate Session object that is lazily initialized by the currentSession() 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.

Figure 6. SessionManager class

Back to Top

5.3 Customizing the Hibernate Configuration File

After finishing the wizard in section 5.2, the hibernate configuration file will be automatically opened. We now need to
customize the configuration file with the information it needs to connect to our database.

1. Select the Use JDBC Driver option.


We are going to specify the JDBC driver that is defined in the Database Explorer. If you haven't configured a
JDBC driver, please read the Database Explorer Quickstart and configure one before continuing.
2. Select your profile in the Connection Profile drop-down.
If you have configured a JDBC driver but not a connection profile, you can select the New Profile button to
create a new connection profile. If you already have a connection profile, when you select it the next four fields
should be filled in automatically.
3. Click the Copy JDBC Driver and add to classpath... link.
4. Select the appropriate Hibernate Dialect for your database.

Your Configuration page should now look like this.

Figure 7. Hibernate Configuration file with Oracle connectivity configured

You may use the Properties section to add and edit properties.
Figure 8. Adding properties

The Mappings section allows you to add mapping files which might already exist in your project.
Figure 9. Adding mapping files

Figure 10 shows the hibernate configuration file source after the above steps have been completed.
Figure 10. Hibernate Configuration File

5.4 Creating a Hibernate Java Table Mapping

This section presents a process that uses the MyEclipse Hibernate tools to forward engineer Java data objects and
mapping definitions from existing database tables.

1. Open the MyEclipse Database Perspective. From the menubar, select Window > Open Perspective >
Other > MyEclipse Database Explorer
2. Open a database connection with the profile that you are using in your Hibernate configuration
3. Browse the database schema until you find a table/entity for which you want to create a Hibernate mapping

Note: In our example we use the BONUS table in the dbtest database.

4. Right-click the table and select Create Hibernate Mapping, as shown in Figure 11. This will launch the
Hibernate Mapping Wizard.
Figure 11. Launching Hibernate Mapping Wizard for echo_message database table

The Hibernate Mapping wizard is shown in Figure 12.


Figure 12. Hibernate Mapping Wizard

Table 4 - Hibernate Mapping Wizard

Field Description

The folder into which the Hibernate mapping files will be placed. Select the
Location
Browse button to specify a location.

Base Persistence Optionally specify the Base class that the new Java mapping classes will
Class extend. Note: This can be left blank.

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
ID Generator
persistent class. See the Resources section for a link to the Hibernate
documentation that describes each of these ID Generator values in detail.

Determines whether Java or Hibernate types will used in the type property of
Types
field mappings, e.g. java.lang.String vs. string

Update Hibernate Enable this option if you want the hibernate.cfg.xml file to be updated with the
Configuration File new mapping element.

1. Select the Location field's Browse button to view available Java packages into which the mapping file can be
created.
2. Select the same package as the SessionManager class.
Figure 13. Mapping File Location Selection

3. Select increment for the ID Generator field. See Table 4 for description of this field.
4. Make sure that Update Hibernate Configuration File option is enabled.
5. Complete the page as shown in Figure 14, and select Finish.

Figure 14. Completed Hibernate Mapping Page

The wizard completion process performs the following actions:


• Creates the AbstractBonus class. This abstract class provides the required Hibernate compatibility features
such as public getter and setter methods for persistent properties corresponding to columns in the bonus
database table, and default method implementations for equals() and hashCode().
• Creates the Bonus Java class, a concrete subclass of AbstractBonus class.. Bonus is intended to be
modified directly with additional business and validation logic.
• Creates the Bonus.hbm.xml Hibernate mapping descriptor. This file instructs Hibernate how to map data
to/from the Bonus Java class and the bonus database table.
• Registers the Bonus.hbm.xml mapping descriptor in the hibernate.cfg.xml file

Figure 15 highlights the two new Java classes, the new mapping descriptor, and the
descriptor's registration in the hibernate.cfg.xml file.

Figure 15. Updated project following Hibernate Mapping Wizard execution

Back to Top

6. Testing the HibernateDemo Application


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 SessionManager created by the Hibernate wizards. Look at the two important methods defined on the
HibernateSession class as shown in Figure 16 that will be used in the test code.
Shown are two important static methods on the HibernateSession class.

currentSession(): 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 the currentSession method to obtain the cached
Hibernate Session.

closeSession(): If a session has been started it simply closes it.

Figure 16. SessionManager


Methods

Following is a list of the steps in the test code along with a sample of the source code

1. Create a new Java class: File > New > Class


2. Fill in package name
3. Type in the name: HibernateTest
4. Make sure the option public static void main(String[] args) is enabled
5. Complete the page as shown in Figure 17 and select Finish
Figure 17. New Java Test Class

6. Next, open the HibernateTest.java file and replace the source code with that listed in Figure 18.

HibernateTest.java

package com.genuitec.hibernate;
import net.sf.hibernate.*;

public class HibernateTest {


public static void main(String[] args) {
// Step 1 - Create a new entity
EchoMessage message = new EchoMessage();
// Step 2 - Set message field
message.setMsg("Hello Hibernate, from MyEclipse!");

try {
// Step 3 - Get a Hibernate Session
Session session = SessionManager.currentSession();
// Step 4 - Persist entity to database
Transaction tx = session.beginTransaction();
session.save(message);
tx.commit();
System.out.println("Save successful.");
} catch (HibernateException e) {
System.out.println("Save failed.");
} finally {
try {
// Step 5 - close the session
SessionManager.closeSession();
} catch (HibernateException e1) {
// do nothing
}
}
}
}

Figure 18. HibernateTest.java Source Code Listing

7. Save HibernateTest.java
8. Select the HibernateTest.java file in the Package Explorer
9. From the Run menu on the top menubar select Run > Run as > Java Application

At this point, the Console View will open, and if the test is successful you will see the following output as shown
in Figure 19. Note: If you see log4j warnings, you can safely ignore them.

Figure 19. HibernateTest Console Output

The object we created in the main method was saved as a record out to the database. You can view your results in the
table using the Database Explorer.

1. Open Database Explorer Perspective: Window > Open Perspective > MyEclipse Database Explorer
2. Connect to the database profile that you are using with your Hibernate application
3. Browse to the table that you have mapped into your Hibernate configuration file
4. Right-click the table and select Generate Select in SQL Editor
5. Run the SQL statement by pressing the icon

The results will be displayed in the SQL Results view, as shown in Figure 20. For more information about
using the MyEclipse Database Explorer, please see the Database Explorer Quickstart.
Figure 20. Viewing Results in the Database Explorer.

Back to Top

7. Summary
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 .

Back to Top
8. User Feedback
If you have comments or suggestions regarding this document please submit them to the MyEclipse Documentation
Forum .

Back to Top

9.Resources
• Download Java 2 SDK, Standard Edition 1.4 from Sun Microsystems.
• Download Eclipse 3.1 SDK or greater from the Eclipse Foundation
• Download the MyEclipse 4.1 30 day trial edition; portal registration is required.
• To learn more about Hibernate visit the official Hibernate Documentation site.
• Visit the MyEclipse Quickstart Library for more MyEclipse tutorials.

Back to Top

Copyright © 2004 - 2005 by Genuitec L.L.C.

You might also like