MyEclipse Logo
 

MyEclipse Hibernate Tutorial

Outline

download the latest MyEclipse version

help and support
 

1. Preface

This document was written using MyEclipse and all screenshots are based upon the default user interface settings for MyEclipse Windows XP. However, 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.


 

2. Requirements

Below is a list of requirements for this Tutorial:

  1. MyEclipse (see Resources for a download link)
  2. A database server that is supported by Hibernate and the MyEclipse Database Explorer such as the embedded Derby database that is shipped within the MyEclipse server sandbox or an externally installed database such as one of the following:
  • Axion
  • Derby
  • Hypersonic DB
  • InstantDB
  • Interclient
  • Firebird
  • ODBC Bridge
  • jTDS
  • Mckoi
  • Microsoft SQL Server
  • Mimer SQL
  • MySQL
  • Oracle
  • Pointbase
  • PostgresQL
  • SAPDB
  • Sunopsis XML
  • Sybase
  • ThinkSQL

3. Introduction

This tutorial 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 Session Factory
  • Generate Java classes and Hibernate database mapping (.hbm) files from Database Explorer table definitions
  • Use the HQL editor
  • Create a small test application that uses Hibernate

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


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 t

To learn more about Hibernate's basic and advanced features, or how to develop with Hibernate, see the Resources section below.

ools 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

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. We have also added a couple of records to the table to facilitate testing.

echo_message DDL
CREATE TABLE echo_message
(
    id integer PRIMARY KEY not null,
    msg VARCHAR(255)
);

insert into echo_message values(1, 'hello world');
insert into echo_message values(2, 'goodbye world');

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 Tutorial tutorial.

Note: Even though this Tutorial uses Oracle, the instructions and the sample table above are generic enough to work with any database.


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 


  5. Figure 1. New HibernateDemo Project


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:

  • Adds the Hibernate libraries (JARs) to the project's classpath.
  • Creates and configures the hibernate.cfg.xml for the project
  • Creates a custom Session Factory 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. Leave the Hibernate 3.2 specification selected.
  4. Select the library sets you desire, for this demo the Core libraries are sufficient.
  5. Leave Add checked Libraries to project build-path selected.
  6. Select Next.

  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.2 is recommended.

Enable Hibernate Annotations support

Available only for Hibernate 3.2, will create an AnnotationConfiguration instead of a regular Configuration in your SessionFactory class. Necessary if you are going to use annotated POJOs instead of Hibernate mapping files.

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.

    Page 2 allows you to customize the name and location of the configuration file.


    Figure 4. Hibernate Configuration File Setup

  1. Leave New selected.
  2. Complete this page as shown in Figure 4 and select Next.


    Figure 5. Hibernate Datasource Configuration

  3. Leave Specify datasource connection details? checked.
  4. Select the Oracle profile you created in the the Database Explorer Tutorial using the DB Profile combo. This will automatically populate all the fields on this page.
    Note: A profile is not necessary at this stage; you may manually fill in all the remaining details as shown on this page, without selecting a profile.
    In this case, you have to make sure you copy the JDBC driver JAR files to your project after the wizard completes.
  5. Select Next.

    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.

  6. Select  Create SessionFactory class.
  7. Select the New button for the package field and create the com.genuitec.hibernate package.
  8. Enter a name for the  Session Factory Class, we use the default HibernateSessionFactory suggestion.
  9. Complete the page as shown in Figure 6, and then select Finish.

    Note: The Session Factory can also be created at a later point by using the Session Factory wizard (File > New > Other MyEclipse > Hibernate > Hibernate Session Factory).
    If you chose to copy libraries to your project on page 1, 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 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


5.3  Customizing the Hibernate Configuration File

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.

  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 Tutorial 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 8. Hibernate Configuration file with Oracle connectivity configured


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

    
Figure 9. Adding properties


The Mappings section allows you to add mapping files which might already exist in your project. Alternatively, dragging and dropping mapping files from the Package Explorer is also supported.

    


Figure 10. Adding mapping files

Figure 11 shows the hibernate configuration file source after the above steps have been completed.


Figure 11. 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 Hibernate Perspective.  From the menubar, select Window > Open Perspective > Other > MyEclipse Hibernate
  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 ECHO_MESSAGE table in the  TEST schema; the procedure for other databases and tables is exactly the same.

  4. Right-click the table and select  Create Hibernate Mapping, as shown in Figure 12. This will launch the Hibernate Reverse Engineering Wizard.
    Alternatively, you can drag tables from the DB Browser view and drop them into the Hibernate Configuration editor to launch the wizard.

    Note: You can select multiple tables in the DB Browser to reverse engineer them at the same time.


    Figure 12. Launching Hibernate Mapping Wizard for ECHO_MESSAGE database table

    The  Hibernate Reverse Engineering wizard is a 3 page wizard.


    Figure 13.  Hibernate Reverse Engineering Wizard - Page 1
  1. Click the Java src folder field's Browse... button to view available Hibernate projects and source folders into which the files can be generated.
    Select the src folder in the HibernateDemo project.
  2. Click the Browse... button for the Java package field to select the com.genuitec.hibernate package
  3. Complete the rest of the wizard as shown in Figure 13 and select Next.

    Note:
    Settings on page 2 and 3 of the wizard are used to customize the reverse engineering process.
    It is possible to start the process without customizing any of the settings on these two pages and simply clicking Finish now.

    Table 4 - Hibernate Reverse Engineering Wizard - Page 1

    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.

    Create POJO<>DB table mapping information

    Generate either mapping files or annotated POJOs from the selected tables.

    Update hibernate configuration

    Add the mapping files / annotated POJOs 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.
    e.g. findByFirstName("name");

    Use custom templates

    Override MyEclipse's internal velocity templates with your own versions.
    See Using templates to fine tune generated code for further details.

    Template directory

    Directory containing the root of the custom template tree.


    Figure 14.  Hibernate Reverse Engineering Wizard - Page 2

  4. The default settings can be used for page 2, select Next.

    Table 5 - 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.
    The wizard will create this file automatically if one cannot be found.

    Custom rev-eng strategy

    Allows you to specify a custom reverse engineering strategy class. This class allows you to programmatically customize various aspects of the reverse engineering process. See Using a custom reverse engineering strategy for further details.

    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.
    If blank or a more specific setting is not made on page 3 of this wizard, the Hibernate mapping engine will choose an ID generator for you.

    Generate basic typed composite IDs

    If a table has a multi-column primary key, a <composite-id> mapping will always be created.

    If this option is enabled and there are matching foreign-keys, each key column is still considered a 'basic' scalar (string, long, etc.) instead of a reference to an entity. <many-to-one> elements are created, but they are marked as non-updatable and non-insertable.

    If you disable this option (recommended default), <key-many-to-one> elements are created instead.

    Generate version and timestamp tags

    If enabled, columns named "version" and "timestamp" are represented as <version> and <timestamp> tags in the generated mapping files.

    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.


  5. Default settings can also be used for page 3, select Finish to start the reverse engineering process.


    Figure 15.  Hibernate Reverse Engineering Wizard - Page 3

    Table 6 - Hibernate Reverse Engineering Wizard - Page 3

    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:

  • Creates the AbstractEchoMessage 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  ECHO_MESSAGE database table.
  • Creates the EchoMessage Java class, a concrete subclass of the AbstractEchoMessage class. EchoMessage is intended to be modified directly with additional business and validation logic and will not be overwritten in subsequent generation passes.
  • Creates the EchoMessage.hbm.xml Hibernate mapping descriptor. This file instructs Hibernate how to map data to/from the EchoMessage Java class and the ECHO_MESSAGE database table.
  • Registers the EchoMessage.hbm.xml mapping descriptor in the  hibernate.cfg.xml file.
  • Creates the EchoMessageDAO Java class. This class provides convenient access to the EchoMessage data object class.
  • Creates the IBaseHibernateDAO interface & BaseHibernateDAO class. These classes are necessary for the functioning of the Basic DAOs and they use the Session factory generated when Hibernate capabilities were added ( com.genuitec.hibernate.HibernateSessionFactory) to obtain Hibernate sessions.

Figure 16 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 16.  Updated project following Hibernate Mapping Wizard execution


5.5 Using templates to fine tune generated code

  • Download and unzip this file to a suitable location on your file system.
  • Follow the instructions in README.txt in the zip file to customize the templates.
  • Invoke the Reverse Engineering wizard and on page 1, enable the Use custom templates option and point the Template directory field to the folder containing the template tree.


5.6 Using a custom reverse engineering strategy

  1. Add the MyEclipse Persistence Tools library to your project.
    • Right click your project and select Properties.
    • On the Java Build Path page, choose Add Library... on the Libraries tab.
    • Choose MyEclipse Libraries and then MyEclipse Persistence Tools.
    • Press Finish.

    Figure 17.  Adding the MyEclipse Persistence Tools library

  2. Create a new class in your project which extends the org.hibernate.cfg.reveng.DelegatingReverseEngineeringStrategy class.
  3. Define the single argument constructor and override a method of interest, for example, columnToPropertyName.
    Here's an example which prefixes all generated propertes with "ME_"
    MyStrategy.java
    package  com.genuitec.hibernate;

    import  org.hibernate.cfg.reveng.DelegatingReverseEngineeringStrategy;
    import  org.hibernate.cfg.reveng.ReverseEngineeringStrategy;
    import  org.hibernate.cfg.reveng.TableIdentifier;

    public class MyStrategy extends DelegatingReverseEngineeringStrategy {

      public MyStrategy(ReverseEngineeringStrategy strategy) {    
        super (strategy);    
      }

      public String columnToPropertyName(TableIdentifier table, String columnName) {    
        return "ME_" + super.columnToPropertyName(table, columnName);    
      } 


    }

  4. On page 2 of the reverse engineering wizard, specify the class you just created

    Figure 18.  Specifying the reverse engineering strategy


5.7 Editing a mapping file

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

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


    Figure 19.  Hibernate Mapping Editor - Design Page


    Figure 20.  Add meta element wizard


    Figure 21.  Hibernate Mapping Editor - Source Page

6. Using the HQL editor


MyEclipse includes a Hibernate Query Language editor and several views that allow you to execute HQL queries against your Hibernate configuration.

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 on the fly.

The following steps will instruct you in the use of the HQL editor
  1. Right click the HibernateDemo project in the Package Explorer.
  2. From the MyEclipse item in the context menu, select Open HQL Editor...
    Note: The HQL editor will also be opened if you attempt to open a file with an hql extension.


    Figure 22.  Opening the HQL editor

  3. If you aren't already in the Hibernate perspective, you will be prompted to switch, do so.
    Note: You may always switch to this perspective by using Window > Open Perspective > Other > MyEclipse Hibernate
  4. When the editor opens, type out "from EchoMessage"
  5. Click the Run icon or press Ctrl + F9 to execute your query.


    Figure 23.  Executing a query in the HQL editor

  6. Use the Query Parameters view to execute a variable query.


    Figure 24.  Using the Query Parameters view

    Note: If you change configuration, mapping or data objects after the HQL editor has been initialized for a particular project, be sure to use the Refresh button on the embedded toolbar to make sure the editor picks up the latest changes.

If you are editing a NamedQuery annotation, you can invoke quick fix (usually Ctrl + 1) inside the query attribute to get a Copy to HQL Editor action. Selecting this action will open the HQL editor, initialized with the query string.

Figure 25.  Copy to HQL Editor action

You can test and edit your query in the HQL editor, when done, closing the editor will allow you to copy the modified query back into the query attribute in the Java editor.

After you open the HQL editor for a given project, content assist and validation will be provided for NamedQueries.

Figure 26. Named query content assist


Figure 27.  Named query validation


7. Using the Criteria editor

In addition to the HQL editor, the MyEclipse Hibernate tools also include a Criteria editor.

For folks unfamiliar with Criteria in Hibernate, it's a way to utilize instances of objects, combined with query constraints to create queries against your entities. For example, creating an entity instance with a type of say "User", and specifying that as a criteria for your query inaddition to telling the Criteria to only return 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 on your project that already has Hibernate Capabilities added to it, go down to the MyEclipse menu and select Open Criteria Editor...



Figure 28.  Opening the Criteria editor

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

In the example below, we create a very simple Criteria based on our EchoMessage entity, asking Hibernate to return the EchoMessage entity having an Id value of 2. We see the result below in the result view.



Figure 29.  Executing a Criteria query

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

Figure 30.  Copy to Criteria editor action

You can test and edit the criteria in the Criteria editor, when done, closing the editor will allow you replace the originally selected text with the modified criteria query. To learn more about writing Criteria, see the Hibernate Criteria documentation.


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


Figure 31. HibernateSessionFactory Methods

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

  1. Create a new Java class: File > New > Class
  2. Fill in package name
  3. Type in the name: HibernateReadTest
  4. Complete the page as shown in Figure 32 and select Finish


    Figure 32. New Java Test Class

  5. Next, open the HibernateReadTest.java file and replace the source code with that listed in the following code block. 

    HibernateReadTest.java
    package  com.genuitec.hibernate;

    import  org.hibernate.HibernateException;

    public class  HibernateReadTest {

      public static  void  main(String[] args) {
        // Step 1 - Create the DAO
        EchoMessageDAO dao = new  EchoMessageDAO();
        try  {
          // Step 2 - Use findById to retrieve the message with ID = 1
          EchoMessage echoMessage = dao.findById(new  Long(1));
          System.out.println("Entity retrieval successful, message is: "
              + echoMessage.getMsg());
        catch  (HibernateException e) {
          System.err.println("Entity retrieval failed.");
          e.printStackTrace();
        finally  {
          try  {
            dao.getSession().close();
          catch  (Exception e) {
            // do nothing
          }
        }
      }

    }


  6. Save HibernateReadTest.java
  7. Select the HibernateReadTest.java file in the Package Explorer
  8. 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 33.
    Note: If you see log4j warnings, you can safely ignore them.


    Figure 33. HibernateReadTest Console Output

9. Using the sample HibernateDemo project

  1. Download HibernateDemo.zip
  2. Choose Import > Existing Projects into Workspace, chose the Select archive file option and point it to the zip file. Press Finish to import it into your eclipse workspace.
  3. You will need to make the following changes to reconfigure the project to match your environment.
    • Copy the JDBC driver JAR for your database into the project. Add it to the build path by right clicking and selecting Build Path > Add to Build Path
    • Establish a connection to your database and execute the code in the DDL/DDL.sql file to create the sample table and populate it.
      Prior to execution, you may need to qualify the table with a schema prefix and make other changes to the DDL specific to your database.
    • Edit hibernate.cfg.xml and change the connection settings to reflect your database setup.
      You may need to change EchoMessage.hbm.xml to change the schema specified in the class element.
The following additional files are included:
log4j.properties is used to control the level of logging performed by the log4j library.
ehcache.xml is used to configure the ehcache library.
HibernateWriteTest.java is a sample application that demonstrates how DAOs may be used to write to your database.


10. Summary

This concludes your introduction to Hibernate Development using MyEclipse. Additional Tutorial 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 Tutorial library.


11. User Feedback

If you have comments or suggestions regarding this document please submit them to the MyEclipse Documentation Forum.


12. Resources