Connecting Tomcat to MySQL or Oracle Using Hibernate

Hibernate is an open-source object and relational mapping framework. It uses a lightweight object encapsulation for JDBC and allows JAVA developers to access data from databases using JAVA objects. Hibernate is designed to run in a managed environment, such as the environment of the web server. With Hibernate, you only need to configure a small part of the environment. Hibernate inherits database connections from the application server. Therefore, it is easy to create an enterprise application that uses Hibernate capabilities in the same way as other capabilities available in the application server. You can obtain Hibernate and Hibernate tools from the product websites. See Table 1 (page 12) for the appropriate links.

This section provides an example demonstrating the use of Hibernate for web applications using a MySQL or Oracle database.

Installing Hibernate, Tomcat, and JDK

Download the Hibernate package, including tools, from the Hibernate website and install it using the instructions provided. See Table 1 (page 12) for the correct version and website link.

Verify that you have installed and configured both Sun JDK and Tomcat before proceeding. For additional information, see “Installing and Configuring Tomcat” (page 17).

Configuring a Database Driver in Tomcat

Verify that MySQL or Oracle are configured as data sources for Tomcat as described in “Connecting Tomcat to a Database” (page 30) before proceeding.

To verify that the mysql-connector-java-<VERSION>.jar or ojdbc14.jar are configured, go to the $CATALINA_HOME/common/lib directory and verify that the corresponding file exists.

Adding Test Data to the Databases

In order to verify that the MySQL or Oracle database interact properly with Tomcat, you must populate the database with test data.

Add test data to the MySQL database using the following steps:

1.Log in to the MySQL command line tool by entering the following command:

# mysql -u root -p <PASSWORD>

2.Create a database named osmsdb and create a table named USERS by entering the following commands:

mysql> create database osmsdb; mysql> use osmsdb;

mysql> create table USERS(

mysql> User_id int(10) auto_increment not null primary key, mysql> First_name varchar(30) not null,

mysql> Last_name varchar(30) not null mysql> );

3.Add a user named osmsusr that uses the password osmspass and grant the appropriate privileges to it by entering the following commands

mysql> create user 'osmsusr'@'%.%.%.%';

mysql> grant all on osmsdb.* to 'osmsusr'@'%.%.%.%' identified \ by 'osmspass';

Add test data to the Oracle database using the following steps:

36