More Books
Hibernate: A J2EE Developer's Guide
Hibernate: A J2EE™ Developer's Guide
Table of Contents
Copyright
Acknowledgments
About the Author
Preface
Required Skills
Roadmap
Chapter 1. Overview
Why Object/Relational Mapping?
What Is Hibernate?
Comparing JDBC to Hibernate
Hibernate's Mapping System
Other Java/Database Integration Solutions
How to Obtain and Install
Supported Databases
Chapter 2. Getting Oriented
Application Architecture
Mapping Files
Generating Java Source
Application Configuration
Web Application
JSP Interface
Chapter 3. Starting from Java
Java Object Model
Generated Mapping Files
Generated Schema
Working with Artifacts and Owners
Chapter 4. Starting from an Existing Schema
Initial Schema
Using Middlegen
Generated Mapping Files
Generated Java
Working with the Database
Chapter 5. Mapping Files
Basic Structure
Mapping File Reference
Chapter 6. Persistent Objects
Sessions
Objects and Identity
Life-Cycle Methods
Chapter 7. Relationships
Database Relationships
Java Collection Relationships
Java Class Relationships
Any-Based Relationships
Bi-directional Relationships
Chapter 8. Queries
HQL
HQL Reference
Select
From
Where
Group By
Having
Order By
Criteria Queries
Native SQL Queries
Chapter 9. Transactions
Introduction to Transactions
Optimistic and Pessimistic Locking
Chapter 10. Performance
Finding and Solving Problems
Queries
Inserts
Connection Pooling
Caching
Chapter 11. Schema Management
Updating an Existing Schema
Generating Update and Drop Scripts
Chapter 12. Best Practices, Style Guide, Tips and Tricks
Reducing Code with Inversion of Control
Reducing Session Creation Impact with ThreadLocal
Using Hibernate as an EJB BMP Solution
Integrating with Other Technologies
Applications That Use Hibernate
Strategies for Getting Started
Chapter 13. Future Directions
Hibernate 3.0
EJB 3.0
Here and Now
Index
SYMBOL
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X

Updating an Existing Schema

The tool net.sf.hibernate.tool.hbm2ddl.SchemaUpdate allows an application to bring a schema up to date with the expected schema based on a set of *.hbm.xml files. Typically, this is used to address a situation in which an incremental update to an application requires a relatively minor change, such as a new property.

Consider, for example, an application with a user object (and corresponding user table). You've decided to add a property to the user object to track the user's country code (previously the application only supported U.S. addresses). You make the change to your *.hbm.xml file and the corresponding Java code, and now would like to reflect the change in the deployed database. This can be done either from the command line, from an Ant task, or embedded within your application.

SchemaUpdate relies heavily on metadata returned by a database driver to understand the existing schema. For this reason, the ability of SchemaUpdate to operate properly can vary from driver to driver (and database to database). If you are unable to use SchemaUpdate with your preferred database, you may wish to use the SchemaExport tool (described later in this chapter) instead.

Schema Updates from within an Application

Listing 11.1 shows an example of SchemaUpdate embedded within an application. Note that a Configuration object is required, but a Session is not (obviously, you should perform any schema manipulation before working with the database).

Listing 11.1. SchemaUpdate Example
package com.cascadetg.ch11;

/** Various Hibernate-related imports */
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;
import net.sf.hibernate.tool.hbm2ddl.SchemaUpdate;

public class SchemaUpdaterExample
{

    /** We use this session factory to create our sessions */
    public static SessionFactory sessionFactory;

    public static void main(String[] args)
    {
        initialization();
    }

    /**
     * Loads the Hibernate configuration information, sets up
     * the database and the Hibernate session factory.
     */
    public static void initialization()
    {
        System.out.println("initialization");
        try
        {
            Configuration myConfiguration = new
                 Configuration();

            myConfiguration
                    .addClass(com.cascadetg.ch03.Owner.class);
            myConfiguration
                    .addClass(com.cascadetg.ch03.Artifact
                         .class);

            // Load the *.hbm.xml files as set in the
            // config, and set the dialect.
            new SchemaUpdate(myConfiguration)
                    .execute(true, true);

        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

Command Line Schema Updates

To use SchemaUpdate from the command line, you have to use the command java net.sf.hibernate.tool.hbm2ddl.SchemaUpdate, passing in one or more of the command-line options shown in Table 11.1, followed by the path to the *.hbm.xml files.

Table 11.1. SchemaUpdate Command-Line Options

--quiet

Echo the script to the console

--properties=

Specify the hibernate.properties file

filename.properties

 

--config=

Specify the hibernate.cfg.xml file

filename.cfg.xml

 

--text

Do not execute the update

--naming= fully.qualified.class.name

Specify the naming policy to use (Hibernate ships with net.sf.hibernate.cfg.Default NamingStrategy (prefers mixed case) and net.sf.hibernate.cfg.ImprovedNamingStrategy (prefers underscores).


Ant Task Schema Updates

In addition to the runtime and command-line options, you can also use a build-time Ant task, as shown in Listing 11.2.

Listing 11.2. SchemaUpdate Ant Task
<target name="schemaupdate">
    <taskdef name="schemaupdate"
        classname="net.sf.hibernate.tool.hbm2ddl
             .SchemaUpdateTask"
        classpathref="class.path"/>

    <schemaupdate
        properties="hibernate.properties"
        quiet="no">
        <fileset dir="src">
            <include name="**/*.hbm.xml"/>
        </fileset>
    </schemaupdate>
</target>