Developing Applications with JBoss and Hibernate: Part 1

Exclusive offer: get 50% off this eBook here
JBoss AS 5 Development

JBoss AS 5 Development — Save 50%

Develop, deploy, and secure Java applications on this robust, open source application server

$29.99    $15.00
by Francesco Marchioni | January 2010 | JBoss Java Open Source

In this article, by Francesco Marchioni, we will introduce Hibernate, which is the de facto standard object-relational mapping framework for Java applications. The Hibernate galaxy is quite large and needs a book of its own to be fully explored. Our mission will be to take over one sector of this galaxy, especially where Hibernate applications are managed by JBoss AS.

In this two-part article, we will cover the following topics:

  • A short introduction to Hibernate
  • Setting up our proof of concept for the Hibernate project
  • Reverse engineering a database schema into Hibernate POJOs and mapping files
  • Deploying the application to JBoss AS
  • Comparing the Hibernate technology with EJB 3 persistence (JPA)

Introducing Hibernate

Hibernate provides a bridge between the database and the application by persisting application objects in the database, rather than requiring the developer to write and maintain lots of code to store and retrieve objects.

The main configuration file, hibernate.cfg.xml, specifies how Hibernate obtains database connections, either from a JNDI DataSource or from a JDBC connection pool. Additionally, the configuration file defines the persistent classes, which are backed by mapping definition files.

This is a sample hibernate.cfg.xml configuration file that is used to handle connections to a MySQL database, mapping the com.sample.MySample class.

<hibernate-configuration>
<session-factory>
<property name="connection.username">user</property>
<property name="connection.password">password</property>
<property name="connection.url">
jdbc:mysql://localhost/database
</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<mapping resource="com/sample/MyClass.hbm.xml"/>
</session-factory>
</hibernate-configuration>

From our point of view, it is important to know that Hibernate applications can coexist in both the managed environment and the non-managed environment. An application server is a typical example of a managed environment that provides services to hosting applications, such as connection pooling and transaction.

On the other hand, a non-managed application refers to standalone applications, such as Swing Java clients that typically lack any built-in service.

In this article, we will focus on managed environment applications, installed on JBoss Application Server. You will not need to download any library to your JBoss installation. As a matter of fact, JBoss persistence layer is designed around Hibernate API, so it already contains all the core libraries.

Creating a Hibernate application

You can choose different strategies for building a Hibernate application. For example, you could start building Java classes and map files from scratch, and then let Hibernate generate the database schema accordingly. You can also start from a database schema and reverse engineer it into Java classes and Hibernate mapping files. We will choose the latter option, which is also the fastest. Here's an overview of our application.

In this example, we will design an employee agenda divided into departments. The persistence model will be developed with Hibernate, using the reverse engineering facet of JBoss tools. We will then need an interface for recording our employees and departments, and to query them as well.

The web interface will be developed using a simple Model-View-Controller (MVC) pattern and basic JSP 2.0 and servlet features.

The overall architecture of this system resembles the AppStore application that has been used to introduce JPA. As a matter of fact, this example can be used to compare the two persistence models and to decide which option best suits your project needs. We have added a short section at the end of this example to stress a few important points about this choice.

Setting up the database schema

The overall architecture of this system resembles the AppStore application that has been used to introduce JPA. As a matter of fact, this example can be used to compare the two persistence models and to decide which option best suits your project needs. We have added a short section at the end of this example to stress a few important points about this choice.

CREATE schema hibernate;
GRANT ALL PRIVILEGES ON hibernate.* TO 'jboss'@'localhost' WITH GRANT
OPTION;
CREATE TABLE `hibernate`.`department` (
`department_id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`department_name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`department_id`)
)
ENGINE = InnoDB;
CREATE TABLE `hibernate`.`employee` (
`employee_id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`employee_name` VARCHAR(45) NOT NULL,
`employee_salary` INTEGER UNSIGNED NOT NULL,
`employee_department_id` INTEGER UNSIGNED NOT NULL,
PRIMARY KEY (`employee_id`),
CONSTRAINT `FK_employee_1` FOREIGN KEY `FK_employee_1` (`employee_
department_id`)
REFERENCES `department` (`department_id`)
ON DELETE CASCADE
ON UPDATE CASCADE
)
ENGINE = InnoDB;

With the first Data Definition Language (DDL) command, we have created a schema named Hibernate that will be used to store our tables. Then, we have assigned the necessary privileges on the Hibernate schema to the user jboss.

Finally, we created a table named department that contains the list of company units, and another table named employee that contains the list of workers. The employee table references the department with a foreign key constraint.

JBoss AS 5 Development

JBoss AS 5 Development Develop, deploy, and secure Java applications on this robust, open source application server
Published: December 2009
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

A new Eclipse project

Now start Eclipse. You don't have a specific project for Hibernate applications, so a utility project (which simply packs the classes in an archive) will be enough. You can reach this option from the menu by going to New | Other | Java EE | Utility Project.

JBoss AS 5 Development

Name the project HibernateProject and target it to JBoss AS 5.0 Runtime. You can leave the default JBoss AS configuration and hit Finish.

Now, we are going to unleash the full potential of Hibernate tools. Select from the menu New | Other | Hibernate | Hibernate Configuration File. The Hibernate configuration contains all of the details for wiring your application to the database. You will be asked for the name and the parent folder of the configuration file. Accept the default hibernate.cfg.xml at the root of your project.

JBoss AS 5 Development

Next, insert the details of your Hibernate configuration. Choose a name for your SessionFactory, which will contain your MySQL connection facets. Remember to check the flag Create a console configuration, so that the wizard will complete the console configuration as the next step.

JBoss AS 5 Development

A console configuration describes how the Hibernate plugin should interact with Hibernate and what configuration files (including the classpath) are needed to load the POJOs, JDBC drivers, and so on. This step is required to make use of query prototyping, reverse engineering, and code generation.

JBoss AS 5 Development

The console wizard will look at the current selection in the IDE and will try to autodetect the settings, which you can approve or modify to suit your needs. For example, you don't need to enter the Configuration file or the Property file if you have just one in your project; Eclipse will select it automatically.

One important selection is the Type option that lets you choose between the Core hibernate configuration (Java classes backed by mapping files), Annotations, or even JPA annotations. We will leave the selected Core option.

Before clicking Finish, select MySQL (InnoDB) as Database dialect in the Options tab. No other changes are required.

JBoss AS 5 Development

Now verify that you have successfully linked to Hibernate by switching to Hibernate Perspective. This view will be composed by a tree of three objects: Configuration, Session Factory, and Database. Choose Database and verify that it expands correctly to show the database tables of your schema.

JBoss AS 5 Development

If you fail to browse the database schema, check that you have correctly set up your Hibernate configuration.

Reversing your schema into Java classes

The next move will be reversing our database schema into Java classes and mapping files. This powerful feature is available from the menu: File | New | Hibernate | Hibernate Reverse Engineering file. You can place this file in a convenient location for your project and choose a name for it. The default name proposed is hibernate.reveng.xml, which looks rather the tile of another fiction movie from G. Lucas.

JBoss AS 5 Development

On the next page, select your Console configuration and choose the tables that will be included in your reverse engineering process. (Hint: You have to hit Refresh first to show the database schema and then click Include....)

JBoss AS 5 Development

What Eclipse has just created for you is a file named hibernate.reveng.xml that should resemble the following code snippet:

<hibernate-reverse-engineering>
<table-filter match-catalog="hibernate" match-name="department"/>
<table-filter match-catalog="hibernate" match-name="employee"/>
</hibernate-reverse-engineering>

If you are smart at noticing variations, you might have discovered a new icon in your toolbar. This is your gateway to the reverse engineering process. (Notice: this icon is visible only in the Hibernate Perspective, you will not be able to find it anywhere else.)

JBoss AS 5 Development

Click on Hibernate's down arrow icon and select Hibernate Code Generation Configurations. In the next dialog, you will first have to create a new Hibernate Code Generation Configuration that will contain all the details of your reverse engineering process. Click on the New button located in the left corner of the wizard.

JBoss AS 5 Development

Now, select your brand new configuration and carefully choose the following options. First, wire the Console configuration to your project (HibernateProject). Then, choose an output directory for your generated files. We would suggest you to point to your src folder. (Be aware that existing files will be overwritten, that's why I just said you have to be careful!)

Just below, you will find the checkbox Reverse engineer from JDBC Connection. If enabled, the tools will reverse engineer the available database using the connection information in the selected Hibernate Console configuration. Check this option and enter the package name for the generated classes, which will be com.packtpub.hibernate. Leave the other text fields to the defaults and move to the tab Exporters.

JBoss AS 5 Development

The Exporters tab menu is used to specify which type of code should be generated. Each selection represents an Exporter that is responsible for generating the code, hence the name.

In the upper area of the dialog, you will notice an interesting checkbox named Generate EJB 3 annotations. We will return to this useful option later. At the moment, what we need is just to check the Domain code and Hibernate XML Mappings options, which will generate the Java POJOs and mapping files respectively.

JBoss AS 5 Development

It took a bit of time to complete all of these steps; however, now your Java classes and configuration files are handy and waiting to be packaged.

Adding Hibernate configuration to your project

The advantage of embedding the Hibernate application in JBoss AS is that you can expose Hibernate SessionFactory through a JNDI tree and modify its configuration at runtime.

This is indeed a great configuration advantage; before the new release of JBoss AS, you had to delegate to an MBean the creation of the Hibernate SessionFactory and its exposure through JNDI.

For example, if you wanted to configure a SessionFactory at the naming context hibernate/SessionFactory, you would have to package your Hibernate application with a file named xxx-service.xml in the META-INF folder. Here's a sample of it:

<server>
<mbean code="org.jboss.hibernate.jmx.Hibernate"
name="jboss.har:service=Hibernate">
<attribute name="DatasourceName">java:/ MySqlDS</attribute>
<attribute name="Dialect">
org.hibernate.dialect.MySQLDialect
</attribute>
<attribute name="SessionFactoryName">
java:/hibernate/SessionFactory
</attribute>
<attribute name="CacheProviderClass">
org.hibernate.cache.HashtableCacheProvider
</attribute>
</mbean>
</server>

This configuration is still valid for pre 5.0 releases of JBoss AS. With the introduction of the new Virtual Deployment Framework (VDF), you now have to provide your SessionFactory configuration using the Hibernate XML schema. For example, if you want to link your SessionFactory to your MySQL database, you have to add the following service-hibernate.xml. (Be aware, the suffix is -hibernate.xml and not –service.xml.)

<hibernate-configuration xmlns="urn:jboss:hibernate-deployer:1.0">
<session-factory name="java:/hibernate/SessionFactory"
bean="jboss.test.har:service=Hibernate,
testcase=TimersUnitTestCase">
<property name="datasourceName">java:/MySqlDS</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<depends>jboss:service=Naming</depends>
<depends>jboss:service=TransactionManager</depends>
</session-factory>
</hibernate-configuration>

The preceding configuration file needs to be stored in the META-INF folder of your Hibernate archive (HAR) file. The structure of the updated project from the Package Explorer is as shown in the following snapshot:

JBoss AS 5 Development

In the next part we will a web client to the project, package and deploy the application, generate EJB 3 using the wizard and compare the Hibernate framework with the JPA persistence standard, showing how the two technologies can be coupled in a single application.

>> Continue Reading: Developing Applications with JBoss and Hibernate - Part 2

[ 1 | 2 ]

 

If you have read this article you may be interested to view :

JBoss AS 5 Development Develop, deploy, and secure Java applications on this robust, open source application server
Published: December 2009
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

About the Author :


Francesco Marchioni

Francesco Marchioni is a Sun Certified Enterprise Architect employed for an Italian company based in Rome. He started learning Java in 1997 and since then has followed the path to the newest application program interfaces released by Sun. He joined the JBoss community in 2000, when the application server was running release 2.x.

He has spent many years as a software consultant, where he has envisioned many successful software migrations from vendor platforms to open source products such as JBoss AS, fulfilling the tight budget requirements of current times.

Over the past 5 years, he has been authoring technical articles for OReilly Media and is running an IT portal focused on JBoss products (http://www.mastertheboss.com).

He has authored the following titles:

He has also co-authored the book Infinispan Data Grid Platform, Packt Publishing (August 2012), with Manik Surtani, which covers all the aspects related to the configuration and development of applications using the Infinispan Data Grid Platform (http://www.packtpub.com/infinispan-data-grid-platform/book).

Books From Packt

Apache Geronimo 2.1: Quick Reference
Apache Geronimo 2.1: Quick Reference

Tomcat 6 Developer's Guide
Tomcat 6 Developer's Guide

GlassFish Administration
GlassFish Administration

MooTools 1.2 Beginner's Guide
MooTools 1.2 Beginner's Guide

JSF 1.2 Components
JSF 1.2 Components

jBPM Developer Guide
jBPM Developer Guide

Spring Persistence with Hibernate
Spring Persistence with Hibernate

Apache Roller 4.0 – Beginner's Guide
Apache Roller 4.0 – Beginner's Guide

No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
a
c
F
5
h
y
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software