Professional Documents
Culture Documents
MyEclipse Hibernate Quickstart
MyEclipse Hibernate Quickstart
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:
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.
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:
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
The database table description that we will map to a Java class is listed below.
echo_message DDL
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
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
Once the HibernateDemo project has been created, we will now add MyEclipse Hibernate capabilities to it. This wizard-
based process performs the following actions:
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.
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
Field Description
Create SessionFactory If enabled, the wizard will create a new class that will provide Hibernate
Class session factory class.
Source Folder Determines the source folder to add the new SessionFactory class.
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.
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.
Back to Top
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.
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
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
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.
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 15 highlights the two new Java classes, the new mapping descriptor, and the
descriptor's registration in the hibernate.cfg.xml file.
Back to Top
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.
Following is a list of the steps in the test code along with a sample of the source code
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.*;
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
}
}
}
}
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.
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