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.

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.

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.

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.

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.

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.

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.

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.

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….)

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.)

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.

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.

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.

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:

Popularity: 2% [?]
No related posts.
Related posts brought to you by Yet Another Related Posts Plugin.
RSS Feed
Twitter

февруари 3rd, 2010
admin
Posted in 

Just thought i would comment and say neat theme, did you code it yourself? Looks great.
Hey, this is a very nice blog! It seems you are doing well in the alexa rankings. If you can please help me jump in the rankings as well by checking out my site at http://www.publicdomainpayday.com thank you so much for your time and I will check back on here when I get a chance!
I usually dont write to blogs but i enjoyed your site and would like to say it. Best wishes. Peter
Great article. There’s a lot of good info here, though I did want to let you know something – I am running Fedora with the latest beta of Firefox, and the look and feel of your blog is kind of bizarre for me. I can read the articles, but the navigation doesn’t work so great.
Hey I just wanted to let you know, I really like the written material on your website. But I am utilising Firefox on a machine running version 9.10 of Crashbang Ubuntu and the design aren’t quite proper. Not a big deal, I can still fundamentally read the articles and search for info, but just wanted to inform you about that. The navigation bar is kind of challenging to apply with the config I’m running. Keep up the superb work!
I want to thank the blogger very much not only for this post but also for his all previous efforts. I found javabg.eu to be greatly interesting. I will be coming back to javabg.eu for more information.
ts really helpfull and informative , Amazing work darragh ..Way of explanation and pictures presentation is attaractive .
Good points raised here, (or rather, those bits I could easily read). I am afflicted with color blindness (deuteranopia to be exact). I use Opera browser (no idea if that matters), and a lot of your site is a little difficult for me to read. I know it is my problem to deal with, in truth, nevertheless it would be kind if you could take into account the color blind when carrying out the next site redesign.
Hey amazing web log, I noticed your web site as I was doing some study on some methods to enhance my web log. I was just wondering what spam software you utilize for comments as I get tons on my site.
Что-то так не получается
Just thought i would comment and say neat design, did you code it yourself? Looks great.
Howdyall . First,allow me to say, great page . I enjoyed reading your blog .. Thanks for the nice info
I really like the fresh perpective you did on the issue. Really was not expecting that when I started off studying. Your concepts were easy to understand that I wondered why I never looked at it before. Glad to know that there’s an individual out there that definitely understands what he’s discussing. Great job
Hi, that was without a doubt an awesome article. I had actually been searching for a photo printing related blog for a while now. Appreciate it! Do you offer a subscription service? because I can’t seem to find the details anywhere.
Your blog is outstanding I will have to read it all, thank you for the diversion from my studies!
ДА, вариант хороший
optimize pc…
Registry Mighty – A Registry Cleaner System Optimizer Suite for Windows Operating Systems…
…
Quite cool! I assist your view!…
hello…
I preferred by way of thanking you for this good article .I by all odds liked every little bit of it. I’ve you bookmarked your web site to see at the modern items you post http://bubu071.livejournal.com/1251.html ,Thanks a lot….
very helpful…
I preferred to thank you for this good article. http://dshkm.blogspot.es/ I by all odds liked every little bit of it…