Java Reference
In-Depth Information
Hibernate does not require you to use an XML configuration file. You have two other
options. First, you can provide a normal Java properties file. The equivalent properties file to
Listing 3-4 would be as follows:
hibernate.connection.driver_class=org.hsqldb.jdbcDriver
hibernate.connection.url=jdbc:hsqldb:file:testdb;shutdown=true
hibernate.connection.username=sa
hibernate.connection.password=
hibernate.connection.pool_size=0
hibernate.show_sql=false
hibernate.dialect=org.hibernate.dialect.HSQLDialect
As you'll notice, this does not contain the resource mapping from the XML file—and in
fact, you cannot include this information in a properties file; if you want to configure Hiber-
nate this way, you'll need to directly map your classes into the Hibernate
Configuration
at
run time. Here's how this can be done:
Configuration config = new Configuration();
config.addClass( sample.entity.Message.class );
config.setProperties( System.getProperties() );
SessionFactory sessions = config.buildSessionFactory();
Note that the
Configuration
object will look in the classpath for a mapping file
in the
same package
as the class it has been passed. So, in this example, where the fully qualified
name of the class is
sample.entity.Message
, you should see the following pair of files from
the root of the classpath:
/sample/entity/Message.class
/sample/entity/Message.hbm.xml
Here,
Message.class
is the compiled output from the
Message.java
code given in Listing 3-5
(and briefly discussed in Chapter 1), and
Message.hbm.xml
is the XML mapping file provided in
Chapter 1 as Listing 1-5. If for some reason you want to keep your mapping files in a different
directory, you can alternatively provide them as resources like this (note that this resource path
must still be relative to the classpath):
Configuration config = new Configuration();
config.addResource( "Message.hbm.xml" );
config.setProperties( System.getProperties() );
SessionFactory sessions = config.buildSessionFactory();
You may have as many or as few mapping files as you wish, given any names you like—
however, it is conventional to have one mapping file for each class that you are mapping, placed
in the same directory as the class itself, and named similarly (for example,
Message.hbm.xml
in
the default package to map the
Message
class also in the default package). This allows you to find
any given class mapping quickly, and keeps the mapping files easily readable.
If you don't want to provide the configuration properties in a file, you can apply them
directly using the
-D
flag. Here's an example:
Search WWH ::
Custom Search