Configure JPA, JNDI and Tomcat

Often you want to configure JPA, JNDI and Tomcat to work together. To let it work together you need to work accurately. One small mistake in the configuration of an item (and I don’t mean a misspelling) and it won’t work. Our configuration needs a couple of resources to work together:

  • persistence.xml
  • web.xml
  • context.xml

Persistence.xml
The persistence.xml connects the data-source to the persistence-unit name as used in the application.

<persistence 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” version=”1.0″>
<persistence-unit name=”JPAService” transaction-type=”RESOURCE_LOCAL”>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<non-jta-data-source>java:comp/env/jdbc/dummy</non-jta-data-source>
<properties>
<property name=”hibernate.hbm2ddl.auto” value=”create” />
<property name=”hibernate.archive.autodetection” value=”class, hbm”/>
<property name=”hibernate.connection.autocommit” value=”false” />
<property name=”hibernate.cache.provider_class” value=”org.hibernate.cache.HashtableCacheProvider”/>
</properties>
</persistence-unit>
</persistence>

Web.xml
You need this when you need a container-managed entity-manager instead of an application-managed entity-manager.

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE web-app
PUBLIC “-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN”
“http://java.sun.com/j2ee/dtds/web-app_2_2.dtd”>

<web-app>

<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/dummy</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

<persistence-context-ref>
<persistence-context-ref-name>jpa/JPAService</persistence-context-ref-name>
<persistence-unit-name>JPAService</persistence-unit-name>
</persistence-context-ref>
</web-app>

Context.xml
This connects the data-source to the used database.

 <?xml version=’1.0′ encoding=’utf-8′?>
<Context path=”/ReqmapFull-1.0.0-SNAPSHOT”
docBase=”/JPAService” debug=”5″
reloadable=”true” crossContext=”true”>

<Logger className=”org.apache.catalina.logger.FileLogger”
prefix=”localhost_yourProjectName_log.” suffix=”.txt” timestamp=”true” />

<Resource name=”jdbc/dummy”
type=”javax.sql.DataSource”
username=”user”
password=”password”
driverClassName=”com.mysql.jdbc.Driver”
url=”jdbc:mysql://localhost:3306/dummy”
/>
</Context>