Advertisements
Hibernation is a state of regulated hypothermia undergone by some animals to conserve energy during the winter.
In this chapter, 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 chapter, 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 chapter, 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.