Map a JavaBean Object to a Database
Are you looking for a simpler, more flexible way to map data representation in a Java object? Try building a Hibernate application for a different approach
by Deepak Vohra
January 24, 2006
Hibernate is an open source object/relational persistence and query service for Java. Data representation in an object model is often required for mapping to a relational data model. You can use Hibernate to map data representation in a Java object to a database, and Hibernate supports several databases including DB2, MySQL, Oracle, and PostgreSQL.
Using Hibernate, you can map Java datatypes to SQL datatypes. Hibernate generates the required SQL to create, update, and delete database tables, and it is used for generating tables from a JavaBean class and adding, retrieving, updating, and deleting data to the tables. Hibernate is preferred over other database persistence technologies, such as Castor, TopLink, and Entity EJB, because it has less complexity, greater flexibility, an open source architecture, and support for different databases without requiring that vendor-specific SQL code must be provided in the data-access layer. Hibernate also provides classes for Ant build tasks. Let's take a look at using Hibernate 3.0 to develop an object/relational application.
The database configuration properties for developing a Hibernate application are specified in the Hibernate properties file (hibernate.properties) or the Hibernate configuration file (hibernate.cfg.xml). These properties specify the database, the JDBC driver class, and the connection URL for connecting to the database. The hbm.xml mapping file specifies the JavaBean properties and the corresponding database columns to which the properties are mapped. The mapping file also specifies the database table name to which a JavaBean class is mapped. The org.hibernate.tool.hbm2ddl.SchemaExport tool is used to map the mapping file to the database table. Here we'll map a mapping file example—Catalog.hbm.xml—that consists of properties for a journal catalog to an Oracle database table—OE.Catalog.
Bring It to the Table
The Hibernate API classes are required to develop a Hibernate application. Download Hibernate 3.0.5, and extract the files to an install directory (see Resources). Install WebLogic Server 8.1, and then install the Oracle 10g Database (see Resources). (Refer to the Oracle 10g Database documentation to install the Oracle database and create a database instance.) Add the JAR files that are required to generate a Hibernate application to the CLASSPATH environment variable (see Resources). The JAR files for developing a Hibernate application are listed in Table 1.
Let's start by generating a database table from a JavaBean class. A database table can be generated with the hibernate.properties file, which specifies the database configuration parameters, and the .hbm.xml mapping file. If a configuration file (hibernate.cfg.xml) is used to specify the database properties, the properties file isn't required. The .hbm.xml mapping file consists of class definitions that specify the JavaBean properties to be mapped to the database table, the database table's name, and its columns corresponding to the JavaBean properties. The column type, length, not-null, and unique attributes are also specified. Some of the mapping file elements are listed in Table 2.
The mapping file example specifies a JavaBean—Catalog.java—that consists of fields and columns for a journal. In the Catalog.hbm.xml mapping file example:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
PUBLIC
"-//Hibernate/Hibernate
Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/
hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Catalog" table=
"OE.CATALOG">
<id name="id" type="string"
column="ID">
<generator class="native"/>
</id>
<property name="journal" column=
"JOURNAL" type="string"/>
<property name="publisher"
column="PUBLISHER" type=
"string"/>
<property name="edition" column=
"EDITION" type="string"/>
<property name="title" column=
"TITLE" type="string"/>
<property name="author" column=
"AUTHOR" type="string"/>
</class>
</hibernate-mapping>
the <generator class="native"/> element specifies the identifier-generation strategy.
The JDBC configuration properties may be specified in the properties file or the configuration file. The properties file is a text file, and properties are specified with <property>=<value>. The configuration file's properties are specified with the <property name="property">value</property> elements. Some of the JDBC configuration properties are listed in Table 3.
The specified driver class in the properties file is oracle.jdbc.driver.OracleDriver, the schema is OE, the connection URL is for the Oracle thin type 4 driver, and the dialect is for the Oracle database:
hibernate.connection.
driver_class=oracle.jdbc.
driver.OracleDriver
hibernate.connection.url=
jdbc:oracle:thin:@<HOST>:
<PORT>:<database>
hibernate.connection.username=OE
hibernate.connection.password=
hibernate.dialect=
org.hibernate.dialect.
OracleDialect
The JDBC properties can be specified in the configuration file instead of the properties file. The mapping file (.hbm.xml) can also be specified in the configuration file (see Listing 1).
Now let's turn to generating an Oracle database table from the Hibernate mapping file (Catalog.hbm.xml) and the properties file (hibernate.properties) by using the org.hibernate.tool.hbm2ddl.SchemaExport tool in the Hibernate toolset.
The Catalog.java JavaBean class that is mapped to the database table is shown in Listing 2. The mapping file specifies the generated database table name. Copy the hibernate.properties and Catalog.hbm.xml files to the same directory—for example, c:/Hibernate. Start the Oracle database, and use the SchemaExport tool to generate the database table:
Hibernate>java org.hibernate.
tool.hbm2ddl.SchemaExport
--properties=
hibernate.properties
Catalog.hbm.xml
When a database table is created, the output from the SchemaExport tool is listed:
drop table OE.CATALOG cascade
constraints
create table OE.CATALOG (ID
varchar2(255) not null,
JOURNAL varchar2(255),
PUBLISHER varchar2(255),
EDITION varchar2(255),
TITLE varchar2(255),
AUTHOR varchar2(255),
primary key (ID))
You can also generate the database table with the configuration file. Copy hibernate.cfg.xml to the same directory where hibernate.properties and Catalog.hbm.xml are stored. Then use the SchemaExport tool to generate the database table.
java org.hibernate.tool.
hbm2ddl.SchemaExport --config=
hibernate.cfg.xml
Now let's see how to use the Hibernate 3.0 API to modify the table data.
Modify the Table
We can develop a Java application to modify data in the table generated from the mapping file. This application integrates the JavaBean class that is generated from the mapping file, the mapping file itself, and the properties file for database persistence. Use the org.hibernate package classes/interfaces to modify the database table, OE.CATALOG, that was generated previously.
Copy the mapping file to the same directory where the Catalog.class, JavaBean class, and the properties file are stored. Add the directory to the CLASSPATH variable. Import the Hibernate API classes into the Java application. These classes are in the org.hibernate package (see Listing 3).
To add data to the database table, create a JavaBean class object that is to be stored in a database. Set the values for the different fields of the Java class with setter methods:
Catalog catalog=new Catalog();
catalog.setId("catalog 1");
catalog.setJournal(
"Oracle Magazine");
catalog.setPublisher(
"Oracle Publishing");
catalog.setEdition(
"Jan-Feb 2004");
catalog.setTitle(
"Understanding Optimization");
catalog.setAuthor(
"Kimberly Floss");
The org.hibernate.Session interface is the main run-time interface between a Java application and Hibernate, and you can use it to create, update, and delete a JavaBean object in a database. A Session object is obtained from a SessionFactory. The SessionFactory interface provides openSession() methods to create a database connection and open a session on the connection, or open a session on a specified connection. Use the org.hibernate.cfg.Configuration class to specify configuration properties, JavaBean persistence class, and mapping files to create a SessionFactory.
Create a Configuration object:
Configuration config=
new Configuration();
Add the Catalog.class JavaBean persistence class to the Configuration:
config.addClass(.Catalog.class);
The Catalog.hbm.xml mapping file and the JDBC properties file, which are in the same directory as the JavaBean class, get configured with the Configuration object. Now, create a SessionFactory object:
SessionFactory sessionFactory=
config.buildSessioFactory();
Next, add data to the database table that was created with the SchemaExport tool. Obtain a Session object from the SessionFactory object:
Session sess =
sessionFactory.openSession();
Obtain a Transaction object from the Session to add data to the database table:
org.hibernate.Transaction tx =
sess.beginTransaction();
Store the JavaBean object in the database with the save() method, and commit the transaction:
sess.save(catalog);
tx.commit();
Close the Session object:
sess.close();
Now let's retrieve data from the database table. Create a Hibernate Query Language (HQL) query to select data from the table. HQL syntax is similar to SQL's syntax. The SELECT clause is not required for a query. The FROM clause in HQL is specified with the JavaBean class instead of the database table:
String hqlQuery =
"FROM Catalog" ;
Open a Session object from the SessionFactory:
Session sess =
sessionFactory.openSession();
Create a Query object with the createQuery(hqlQuery) method of the Session object:
Query query =
sess.createQuery(hqlQuery);
Then obtain a list from the HQL query by using the list() method of the Query object:
List list = query.list();
Iterate over the list and output values for the specified HQL query. For example, the Journal column value is output with:
for (int i = 0; i < list.size();
i++) {
Catalog catalog =
(Catalog) list.get(i);
System.out.println(
"CatalogId " +
catalog.getId() +
" Journal: " +
catalog.getJournal());
}
Change the Data
You can use the Hibernate API to update the database table values. Create an HQL query to select the data that is to be modified:
String hqlQuery="from Catalog";
Obtain a Session object from the SessionObject:
Session sess =
sessionFactory.openSession();
Obtain a Transaction object from the Session object:
Transaction tx =
sess.beginTransaction();
Create a Query object from the HQL query. Obtain a list result set with the list() method, and obtain the JavaBean object to be modified:
Query query =
sess.createQuery(hqlQuery);
List list = query.list();
Catalog catalog =
(Catalog) list.get(0);
As an example, you can set the value of the publisher field to "Oracle Magazine":
catalog.setPublisher(
"Oracle Magazine");
Begin a Session transaction:
Transaction tx =
sess.beginTransaction();
Update the database table with the saveOrUpdate() method of the Session object, and commit the transaction:
sess.saveOrUpdate(catalog);
tx.commit();
Now let's delete a table row with the Hibernate API. As an example, we'll delete the table row for the March-April 2005 edition. Create an HQL query that selects a database table row to delete:
String hqlQuery=
"from Catalog as catalog where
catalog.edition=
'March-April 2005'";
Use the openSession() method to open a database session of the SessionFactory object:
Session sess =
sessionFactory.openSession();
Use the HQL query to create a Query object. Obtain the result set list for the HQL query, and obtain the result set item to be deleted:
Query query = sess.createQuery(
hqlQuery);
List list = query.list();
Catalog catalog =
(Catalog) list.get(0);
Begin a session transaction:
Transaction tx =
sess.beginTransaction();
Use the delete() method of the Session object to delete the row specified in the HQL query, and commit the transaction:
sess.delete(catalog);
tx.commit();
See Listing 3 for the Hibernate3.java Java application example.
Object/relational mapping without a database persistence and query service requires JDBC and vendor-specific SQL scripts to create, update, and delete database tables. With Hibernate, the JDBC API and the SQL scripts are not required. In the application example presented here a JavaBean is mapped to the Oracle database. You can map to another database by specifying the corresponding database dialect in the hibernate.properties file or the hibernate.cfg.xml configuration file.
About the Author
Deepak Vohra is a Sun-certified Java programmer and Sun-certified Web component developer, who has published numerous articles in industry publications and journals. Contact Deepak at .
|