Chapter 6. Hibernate on JBoss Web Server

Hibernate is an object-relational mapping framework. It is packaged independently from Red Hat JBoss Web Server. This packaged version is used on all supported platforms.
Hibernate is used in the same way it is used for a regular Tomcat installation: the Hibernate JAR files are added into a deployment WAR file. Tomcat provides a default connection pooling mechanism, which is defined in context.xml. However, persistence.xml and web.xml are also required. The example below shows a configuration with the Tomcat connection pooling mechanism.
  • /META-INF/context.xml defines the connection pools Tomcat should create.

    Example 6.1. context.xml

    <Context>
      <Resource
        name="jdbc/DsWebAppDB"
        auth="Container"
        type="javax.sql.DataSource"
        username="sa"
        password=""
        driverClassName="org.h2.Driver"
        url="jdbc:h2:mem:target/test/db/h2/hibernate"
        maxActive="8"
        maxIdle="4"/>
    </Context>
  • /WEB-INF/classes/META-INF/persistence.xml is a JPA configuration file. It defines how the application configures Hibernate to consume connections from the Tomcat pool. If you are using the Hibernate API directly, use a similar configuration to that shown in hibernate.cfg.xml.

    Example 6.2. persistence.xml

    <persistence version="1.0"
      xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
    
      <persistence-unit name="dswebapp">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <properties>
          <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
          <property name="hibernate.connection.datasource" value="java:comp/env/jdbc/DsWebAppDB"/>
        </properties>
      </persistence-unit>
    </persistence>
  • /WEB-INF/web.xml is a regular web application deployment file, which instructs Tomcat which datasource to consume. In the example below, the datasource is jdbc/DsWebAppDB.

    Example 6.3. web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    
     <resource-env-ref>
      <resource-env-ref-name>jdbc/DsWebAppDB</resource-env-ref-name>
      <resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
     </resource-env-ref>
    </web-app>
For details, see the Hibernate documentation for JBoss Web Server.