EclipseLink/Examples/JPA/Tomcat Web Tutorial

From Eclipsepedia

Jump to: navigation, search


EclipseLink JPA Deployed on Tomcat 6 using Eclipse WTP

Tomcat 6 is not a JEE5 compliant server by design as it is a servlet container, however the servlet container is able to run EJB 3.0/JPA applications in application-managed SE (stand alone) mode.

If you want to get a small JPA web application running quickly on Tomcat - the services provided by the Web Tools Project plugin in the Eclipse IDE can take care of the deployment details and set the server into debug mode for you.

This basic example details how to use Eclipse to run/debug a minimum JPA Application Managed web application servlet using EclipseLink JPA as the persistence provider. The goal of this example is to detail the minimum steps needed to run EclipseLink inside Tomcat using the Eclipse IDE - at this point no presentation/controller layer such as JSF, Spring or Struts will be used beyond a basic HttpServlet so we can concentrate on the the integration layer JPA setup.


Development Environment

Software: Eclipse IDE for Java EE 3.4 M5 Ganymede (Feb 2008) with all 5 packages (DTP 1.6, EMF 2.4, GEF 3.4, WTP 3.0, XSD 2.4), Oracle 11g DB, Java JDK 1.6.0_04, Apache Tomcat 6.0.18

This example will run fine with Eclipse 3.3 EE and any Database that EclipseLink supports.


Install Eclipse EE

  • I installed a clean version of Eclipse Ganymede M5 with all of WTP 3.0

Install a Database

  • In this example I am using Oracle 11g, the table schemas have already been created manually and all entity java classes have been generated using the Eclipse DALI tool.

Install the Tomcat 6 Web Container

  • TOMCAT_HOME=C:/opt/tomcat6
  • I installed the version that runs as a windows service but disable the service when running the server from the Eclipse IDE.
  • Note: The Tomcat 6 install asks for a Java 1.5 JRE but you can use a Java 1.6 JRE no problem.

Limitations to JPA

  • As Tomcat is not a JEE5 compatible server, there are some limitiations to JPA.
    • No dynamic weaving (instrumentation) - static weaving of entities is still available via EclipseLink
    • No @EJB injection of a session bean (containing the EntityManager) is available - use the persistence factory and manager directly
    • No @PersistenceContext injection of a container managed persistence unit is available - use Persistence.createEntityManagerFactory(JTA_PU_NAME)

Tomcat configuration Changes

JNDI Datasource Setup

Non-JTA Datasource

  • Follow the same setup as the JTA datasource below, except that the transaction-type in persistence.xml is "RESOURCE_LOCAL"
  • After all the server and war configuration below - you will see the following logs when connecting to your non-JTA datasource.
[EL Finest]: 2009-06-01 15:19:23.828--ServerSession(13961193)--Thread(Thread[http-8080-1,5,main])--property=javax.persistence.nonJtaDataSource; value=java:comp/env/ds/OracleDS
[EL Finest]: 2009-06-01 15:19:23.844--ServerSession(13961193)--Thread(Thread[http-8080-1,5,main])--property=eclipselink.session.customizer; value=org.eclipse.persistence.example.unified.integration.JPAEclipseLinkSessionCustomizer
_JPAEclipseLinkSessionCustomizer: configured java:comp/env/ds/OracleDS
[EL Info]: 2009-06-01 15:19:23.844--ServerSession(13961193)--Thread(Thread[http-8080-1,5,main])--EclipseLink, version: Eclipse Persistence Services - 2.0.0.qualifier
[EL Config]: 2009-06-01 15:19:23.859--ServerSession(13961193)--Connection(6427893)--Thread(Thread[http-8080-1,5,main])--connecting
        user name=> ""
        connector=>JNDIConnector datasource name=>java:comp/env/ds/OracleDS
[EL Config]: 2009-06-01 15:19:24.327--ServerSession(13961193)--Connection(24968504)--Thread(Thread[http-8080-1,5,main])--Connected
: jdbc:oracle:thin:@y.y.y.y:1521:orcl
        User: SCOTT
        Database: Oracle  Version: Oracle Database 10g Enterprise Edition Release - Production
With the Partitioning, OLAP and Data Mining options
        Driver: Oracle JDBC driver  Version:
EL Info]: 2009-06-01 15:19:24.358--ServerSession(13961193)--Thread(Thread[http-8080-1,5,main])--file:/C:/opt/tomcat6018/webapps/UnifiedTomcatWeb/WEB-INF/classes/-statJPA login successful

JTA Datasource

Note: in this example as a redirection test I setup the local link to the global JNDI name to be ds/OracleDS but the global name really is also ds/OracleDS for WAR applications that do not override this value.

JTA transaction support is not really supported, even though the datasource is listed as a jta-data-source in persistence.xml it acts as a non-jta-data-source. Tomcat does not support container managed transactions by design. You will need to install Atomikos or JTOM.


There are 2 steps on the server in configuring a JTA JNDI JDBC Datasource in Tomcat 6.

Note: the JNDI name "ds/OracleDS" in web.xml, server.xml and persistence.xml must all match.

  • 1) configure a new global resource in conf/server.xml

Add the following <Resource> element to <GlobalNamingResources>.

  • 2) configure a datasource context for the WAR in conf/server.xml

To link the name ds/OracleDS to the jndi global name ds/OracleDS for WAR consumption, add the following <Context> element inside the <Host> element. The attributes displayName, docBase, path, ResourceLink:global and ResourceLink:name need to be modified.

Note: docBase is very important - it must match your WAR file or you will get a (Name ds is not bound in this Context) exception

  cookies="true" crossContext="false" debug="0"
  privileged="false" reloadable="false"
  swallowOutput="false" useNaming="true"

Downloading EclipseLink Libraries

Download EclipseLink using HTTP - recommended

Download EclipseLink using Maven

See the repository on

Download EclipseLink using SVN - developers only

Persistence JAR location

  • Since Tomcat does not have an EJB container - you must add EJB 3.0/JPA 1.0 capability for EclipseLink JPA by placing the specification persistence.jar into the container lib directory $TOMCAT_HOME/lib
  • I put persistence_1_0.xsd there as well to be safe.
  • It is not recommended that the WAR include its own version of persistence.jar.
  • Your eclipse project should reference but not include this jar and xsd.

EclipseLink JAR location

  • The eclipselink.jar should be placed off of the container lib directory $TOMCAT_HOME/lib
  • Since Tomcat does not include an EJB container, you may put eclipselink.jar in the web applications's lib directory or higher up in the classloader by putting it off of Tomcats' lib directory, where all web applications can access it.
  • Do not split the eclipselink.jar from the javax.persistence jar - keep them together - preferably in $TOMCAT_HOME/lib

JDBC JAR location

Jars for Oracle 11, MySQL 5 and Sybase 5.5/6.0 are off the container lib directory $TOMCAT_HOME/lib

Create Tomcat Server in Eclipse

Open the servers view New | Server | Apache | Tomcat 6.

Create Dynamic Web application

Create your own J2EE WEB Application as below - WAR not EAR. File | new | project | Web | Dynamic Web Project

persistence-context-ref in web.xml

After the servlet and servlet-mapping elements, place the following persistence-context-ref in your tomcat applications' web.xml so the web application has a reference to the eclipselink persistence unit.


resource-ref in web.xml

After the servlet and servlet-mapping elements, place the following resource-ref in your tomcat applications' web.xml so the web application has a reference to the JNDI datasource.

Note: the JNDI name "ds/OracleDS" in web.xml, server.xml and persistence.xml must all match.

      <description>DB Connection</description>

Persistence Unit usage in the WAR

  • Since we dont have access to @EJB or @PersistenceContext injection we must directly create or own persistence unit in the servlet or on a helper class like an ApplicationService (that is not a session bean)
public class FrontController extends HttpServlet implements Servlet {
  public ApplicationService applicationService = null;
  public FrontController() {
    applicationService = new ApplicationService();
public class ApplicationService implements ApplicationServiceLocal {
  public EntityManagerFactory emf  = null;
  public EntityManager entityManager = null;
  public static final String JTA_PU_NAME = "statCreateTablesJTA";
  public ApplicationService() {
    emf  = Persistence.createEntityManagerFactory(JTA_PU_NAME);
    entityManager = emf.createEntityManager();

Session Customizer

Any application server that is based on the Tomcat servlet container like JBoss, Geronimo (defaults to Jetty but includes Tomcat as a secondary web container), WebSphere CE (based on Geronimo) and GlassFish - SUN was the originator of Tomcat and extended it with Grizzly and Tomcat itself requires a STRING_LOOKUP type set on the JNDIConnector class to function properly with JTA - see enhancement request 260383.

If the persistence unit transaction-type is JTA as opposed to RESOURCE_LOCAL then the following session customer will be required to modify the connector.

  • The client will require an implementation of SessionCustomizer that will set the lookupType on the JNDI connector to STRING_LOOKUP instead of Composite.

This will avoid the exception(sic "throught") javax.naming.NamingException: This context must be accessed throught a java: URL

Note: the JNDI name "ds/OracleDS" in web.xml, server.xml and persistence.xml must all match.

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import org.eclipse.persistence.config.SessionCustomizer;
import org.eclipse.persistence.sessions.DatabaseLogin;
import org.eclipse.persistence.sessions.JNDIConnector;
import org.eclipse.persistence.sessions.Session;
import org.eclipse.persistence.sessions.server.ServerSession;
 * See
 * Use for clients that would like to use a JTA SE pu instead of a RESOURCE_LOCAL SE pu.
public class JPAEclipseLinkSessionCustomizer implements SessionCustomizer {
   * Get a dataSource connection and set it on the session with lookupType=STRING_LOOKUP
  public void customize(Session session) throws Exception {
   JNDIConnector connector = null;
   Context context = null;
   try {
    context = new InitialContext();
    if (null != context) {
      connector = (JNDIConnector)session.getLogin().getConnector(); // possible CCE
      // Note: if both jta and non-jta elements exist this will only change the first one - and may still result in the COMPOSITE_NAME_LOOKUP being set
      // Make sure only jta-data-source is in persistence.xml with no non-jta-data-source property set
      // Or, if you are specifying both JTA and non-JTA in your persistence.xml then set both connectors to be safe
      JNDIConnector writeConnector = (JNDIConnector) session.getLogin().getConnector();
      JNDIConnector readConnector = (JNDIConnector) ((DatabaseLogin)((ServerSession)session).getReadConnectionPool().getLogin()).getConnector();
      System.out.println("_JPAEclipseLinkSessionCustomizer: configured " + connector.getName());
    } else {
      throw new Exception("_JPAEclipseLinkSessionCustomizer: Context is null");
   } catch (Exception e) {


20081107: Note use of a JTA datasource configuration is currently only working outside the Eclipse IDE when Tomcat 6 is run as a service - RESOURCE_LOCAL is fine.

If you use a RESOURCE_LOCAL persistence unit configuration you will be able to debug within eclipse. In both JTA and RESOURCE_LOCAL you may deploy the WAR to Tomcat but in the JTA case - Tomcat must run as service and not as a server in the Eclipse IDE.

  • Make sure that your persistence.xml (and optionaly orm.xml) file is placed off of the src/META-INF directory and not the default WebContent/META-INF dir so that it gets picked up by the servlet classloader from the classes directory.
  • Entity classes must be explicitly listed as they will not be automatically discovered by the servlet container - since we are not running our EJB 3 entities in an EJB container.
  • Notice there is no target-server element for the Tomcat 6 web container as target-server is reserved for J2EE compliant EJB container servers.

JTA Persistence.xml

  • Notice there are no standard SE JDBC properties for the database url, username, password - I have shown a JTA datasource example.
  • Also notice there is no target-server property because Tomcat does not support container managed transactions. If you require full JTA support you will need to add support for an ExternalTransactionController and implement a org.eclipse.persistence.transaction.tomcat.TomcatTransactionController(I have not tested this) or move to a fully JEE5 compliant container.
  • Therefore even though we specify JTA, this entityManager is not really JTA because we don't have container management of the transactions. We still need to supply the following wrappers around any update or persist
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="" xmlns:xsi="" xsi:schemaLocation="">
 <persistence-unit name="statCreateTablesJTA" transaction-type="JTA">
   <!--.....list all entities         -->
    <property name="eclipselink.session.customizer" value="org.eclipse.persistence.example.unified.integration.JPAEclipseLinkSessionCustomizer"/>        
    <property name="eclipselink.logging.level" value="FINEST"/> 
    <!-- uncomment the following once - if you wish to have your database tables created by EclipseLink ->           
    <!-- property name="eclipselink.ddl-generation" value="drop-and-create-tables"/-->
    <!-- property name="eclipselink.ddl-generation.output-mode" value="database"/-->

non-JTA (RESOURCE_LOCAL) Persistence.xml

  • You may use a JNDI datasource external connection pool defined in Tomcat (do not use standard SE JDBC properties for the database url, username, password even though the transaction-type is RESOURCE_LOCAL).
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="" xmlns:xsi="" xsi:schemaLocation="">
 <persistence-unit name="statJTA" transaction-type="RESOURCE_LOCAL">
   <!--.....list all entities         -->
    <property name="eclipselink.session.customizer" value="org.eclipse.persistence.example.unified.integration.JPAEclipseLinkSessionCustomizer"/>        
    <property name="" value=""/>            
    <!--  this one overrides -->
    <property name="javax.persistence.nonJtaDataSource" value="java:comp/env/ds/OracleDS"/>
    <property name="eclipselink.logging.level" value="FINEST"/> 

Direct connection (RESOURCE_LOCAL) Persistence.xml

  • You may use standard SE JDBC properties for the database url, username, password - I have shown a RESOURCE_LOCAL JDBC example.
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="" xmlns:xsi="" xsi:schemaLocation="">
 <persistence-unit name="statCreateTablesJTA" transaction-type="RESOURCE_LOCAL">
   <!--.....list all entities         -->
        <!-- there is no need for JNDI customization for a direct connection -->
        <!-- property name="eclipselink.session.customizer" value="org.eclipse.persistence.example.unified.integration.JPAEclipseLinkSessionCustomizer"/-->        
        <!-- property name="" value=""/>            
        <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.driver.OracleDriver"/>
        <property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@"/>
        <property name="javax.persistence.jdbc.user" value="ttocs"/>
        <property name="javax.persistence.jdbc.password" value="password"/>
    <property name="eclipselink.logging.level" value="FINEST"/> 
    <!-- uncomment the following once - if you wish to have your database tables created by EclipseLink ->           
    <!-- property name="eclipselink.ddl-generation" value="drop-and-create-tables"/-->
    <!-- property name="eclipselink.ddl-generation.output-mode" value="database"/-->

Start Tomcat Server

  • Steps: Select the WAR and [Run on Server].
  • The first "Run on Server" may not start the server, in this case you "Start Server" and then "Run on Server".
  • Or optionaly, export your WAR to the $TOMCAT_HOME/webapps directory.
    • When the tomcat server is started up you will see the predeploy messages(here via Eclipse).
    • When tomcat is started as a service here it will expand out the WAR into a dir based on its context name.

[EL Finest]: 2008.11.07 15:04:30.061--ServerSession(24769387)--Thread(Thread[http-8080-1,5,main])--Begin predeploying Persistence Unit statCreateTablesJTA; state Initial; factoryCount 0
[EL Finest]: 2008.11.07 15:04:30.107--ServerSession(24769387)--Thread(Thread[http-8080-1,5,main])--property=eclipselink.weaving; value=false
[EL Finest]: 2008.11.07 15:04:31.327--ServerSession(24769387)--Thread(Thread[http-8080-1,5,main])--End predeploying Persistence Unit statCreateTablesJTA; state Predeployed; factoryCount 0
[EL Finer]: 2008.11.07 15:04:31.327--Thread(Thread[http-8080-1,5,main])--JavaSECMPInitializer - transformer is null.
[EL Finest]: 2008.11.07 15:04:31.421--ServerSession(24769387)--Thread(Thread[http-8080-1,5,main])--property=eclipselink.session.customizer; value=org.eclipse.persistence.example.unified.integration.JPAEclipseLinkSessionCustomizer
_JPAEclipseLinkSessionCustomizer: configured java:/comp/env/ds/OracleDS
[EL Info]: 2008.11.07 15:04:31.421--ServerSession(24769387)--Thread(Thread[http-8080-1,5,main])--EclipseLink, version: Eclipse Persistence Services - ***
[EL Config]: 2008.11.07 15:04:32.952--ServerSession(24769387)--Connection(10577597)--Thread(Thread[http-8080-1,5,main])--connecting(DatabaseLogin(
	user name=> ""
	connector=>JNDIConnector datasource name=>java:/comp/env/ds/OracleDS
[EL Info]: 2008.11.07 15:04:32.999--ServerSession(24769387)--Thread(Thread[http-8080-1,5,main])--file:/C:/opt/tomcat6/webapps/unified/WEB-INF/classes/-statCreateTablesJTA login successful

Publish EAR

Note: If you notice that changes to persistence.xml in build/classes/META-INF/persistence.xml are not in sync with src/META-INF/persistence.xml - make sure Project | build automatically is checked in the Eclipse IDE.

Perform Object Inserts and a JPQL query

Insert Objects

Note: the application managed transactional state methods - hence the same code whether run as JTA or RESOURCE_LOCAL in the case of Tomcat.

 // Store objects        
 // Use an extended DTO wrapper around one of the entities
 LabelDTO aLabelDTO = new LabelDTO((StatLabel)aLabel);
 out.println("Inserted: <i>" + aLabelDTO + " </i><br/>");

[EL Finest]: 2008.11.07 15:04:33.046--UnitOfWork(23761956)--Thread(Thread[http-8080-1,5,main])--PERSIST operation called on:
[EL Fine]: 2008.11.07 15:04:33.265--ClientSession(13266154)--Connection(1923370)--Thread(Thread[http-8080-1,5,main])--INSERT INTO STAT_LABEL (ID, DATE_STAMP) VALUES (?, ?)
	bind => [5827, null]
[EL Fine]: 2008.11.07 15:04:33.296--ClientSession(13266154)--Connection(1923370)--Thread(Thread[http-8080-1,5,main])--INSERT INTO STAT_CLASS (ID, TEST, VERSION, MODIFIED, JDK_VERSION, NAME, CLASS_TYPE_CODE, LINES, INTERNAL, CLASS_PACKAGE, LABEL, CLASS_TYPE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
	bind => [15826, 0, null, 3908-04-30, null, ConcreteClass1, null, null, null, 3827, 5826, null]
[EL Finer]: 2008.11.07 15:04:33.312--UnitOfWork(23761956)--Thread(Thread[http-8080-1,5,main])--end unit of work commit

Query for Objects

 aQuery = entityManager.createQuery("select object(e) from StatLabel e");
 aResultsList = aQuery.getResultList();
[EL Finest]: 2008.11.07 15:04:33.609--UnitOfWork(23761956)--Thread(Thread[http-8080-1,5,main])--Register the existing object

Browser Output

Tomcat eclipselink jpa demo cap.JPG

Using JNDI outside the Tomcat container for J2SE Applications

  • Notice: that the JNDI name for this SE Java application uses java:/comp/env/ds/OracleDS with an extra / before comp that is not defined in the datasource above in persistence.xml. This is OK because we are binding our own subcontext here.
  • Note: this section is a reference for developers that wish to use the same JNDI datasource available in the web container for their standalone SE or JUnit application - outside the web container.
  • When running JUnit SE code against a datasource I usually just specify the .jdbc. elements in persistence.xml - but I am curious about reusing the JNDI datasource that is available to in-container servlets.
  • If you want to test code running outside the container against the Tomcat JNDI provider - like in a JUnit SE test case then you will need to do the following which has been verified on a SE stand alone JPA app using EclipseLink as the JPA provider and Tomcat 6 as the JNDI datasource provider.
  • Setup a JNDI datasource factory/proxy to configure your System properties picked up by (new InitialContext()), create a context using these properties, create all the sub contexts java:, java:/comp etc.. , create a pooled DataSource and bind it to your context before you attempt to use the context.
  • persistence.xml (J2SE only)
<persistence-unit name="statJPA" transaction-type="RESOURCE_LOCAL">
 <!-- persistence-unit name="statJPA" transaction-type="JTA"-->
 <!-- jta-data-source>java:/comp/env/ds/OracleDS</jta-data-source-->
 <class>org.eclipse....list all entities</class>
  <property name="eclipselink.logging.level" value="FINEST"/>            
  • Add the following jars to your out-of-container SE app
 <classpathentry kind="lib" path="C:/opt/tomcat6/bin/tomcat-juli.jar"/>
 <classpathentry kind="lib" path="C:/opt/tomcat6/bin/bootstrap.jar"/>
 <classpathentry kind="lib" path="C:/opt/tomcat6/lib/catalina.jar"/>

SE Source

  • Add the following piece of SE DS configuration code to your non-WAR out-of-container SE class
  • (from Randy Carver at SUN - thank you)

public void configureDataSource()  {
 Context aContext = null;
 // Randy Carver START
 try {
  System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "");
  System.setProperty(Context.URL_PKG_PREFIXES,  "org.apache.naming");            
  InitialContext ic = new InitialContext();
  OracleConnectionPoolDataSource ds = new OracleConnectionPoolDataSource();
  // Globally scoped DataSource
  ic.bind("java:/comp/env/ds/OracleDS", ds);
  // Application scoped DataSource - may require web.xml and ejb-jar.xml customization by container
  //ic.bind("java:/app/jdbc/ds/OracleDS", ds);
 } catch (Exception e) { // refactor
 // Randy Carver END
 try {    
  aContext = new InitialContext();//aHashTable);   
  // Local
  datasource = (javax.sql.DataSource) aContext.lookup ("java:/comp/env/ds/OracleDS");
  if(null == datasource) {
    System.out.println(">> Local DataSource is null");
  } else {
    Connection aConnection = datasource.getConnection();
    System.out.println(">> Local DataSource Connection: " + datasource.toString());
    if(null != aConnection) {
 } catch (Exception e) {   
  try {
   if(null != aContext) {
  } catch (Exception e2) {    


  >> Local DataSource Connection: oracle.jdbc.pool.OracleConnectionPoolDataSource@15b0afd
  • Start tomcat (so we can connect via JNDI)
  • Run your SE app (outside the web container)


  • Original EclipseLink build 20080808 - Michael.OBrien


  • 20090601: updated non-JTA datasource configuration to include resource-ref config on web.xml