MyEclipse Hibernate Quickstart

转自:
http://myeclipseide.com/enterpriseworkbench/help/index.jsp?topic=/com.genuitec.myeclipse.doc/html/quickstarts/webprojects/index.html

今天做的小练习:讲的很仔细!!!


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


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

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:

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

FieldDescription

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.


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


    Figure 4. Hibernate Configuration File Setup

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


    Figure 5. Hibernate Datasource Configuration

  4. Leave Specify datasource connection details? checked.
  5. Select the Oracle profile you created in the the Database Explorer Quickstart 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.
  6. 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

    FieldDescription

    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.

  7. Select  Create SessionFactory class.
  8. Select the New button for the package field and create the com.genuitec.hibernate package.
  9. Enter a name for the Session Factory Class, we use the default HibernateSessionFactory suggestion.
  10. 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

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

    FieldDescription

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

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

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

  • 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 16.  Hibernate Mapping Editor

Back to Top


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 17.  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 18.  Executing a query in the HQL editor

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


    Figure 19.  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.

Back to Top

7. 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 18 that will be used in the test code.


Figure 18. 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 19 and select Finish


    Figure 19. New Java Test Class

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

    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
          }
        }
      }

    }
    Figure 20. HibernateTest.java Source Code Listing

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


    Figure 21. HibernateReadTest Console Output

Back to Top


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

Back to Top


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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值