Chapter 5. Hibernate on Enterprise Web Server

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

    Example 5.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 Hibernate API directly, use a similar configuration in hibernate.cfg.xml.

    Example 5.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 tells Tomcat which datasource it consumes. In Example 5.3, “web.xml” the datasource is jdbc/DsWebAppDB.

    Example 5.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, refer to the Hibernate documentation for JBoss Enterprise Web Server.