Skip to main content
Jump to: navigation, search

Difference between revisions of "EclipseLink/Examples/JPA/Tomcat Web Tutorial"

m (Download EclipseLink using SVN - developers only)
m (Replacing page with '=EclipseLink JPA Deployed on Tomcat 6 using Eclipse WTP=')
Line 1: Line 1:
=EclipseLink JPA Deployed on Tomcat 6 using Eclipse WTP=
=EclipseLink JPA Deployed on Tomcat 6 using Eclipse WTP=
Tomcat 6 is not a JEE5 compliant server by design as it is only 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.
===<font color="green">Install Eclipse EE</font>===
*I installed a clean version of Eclipse Ganymede M5 with all of WTP 3.0
===<font color="green">Install a Database</font>===
*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.
===<font color="green">Install the Tomcat 6 Web Container</font>===
*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===
===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 '''jdbc/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.  Tomcat does not support container managed transactions by design.  You will need to install Atomikos or JTOM.''
There are 2 steps to configuring a JTA JNDI JDBC Datasource in Tomcat 6.
*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 jdbc/OracleDS to 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.
  cookies="true" crossContext="false" debug="0"
  path="/unified" privileged="false" reloadable="false"
  swallowOutput="false" useNaming="true"
==Downloading EclipseLink Libraries==
===Download EclipseLink using HTTP - recommended===
*Proceed to the following URL and download the latest which contains everything you need.
***'''Click on the "EclipseLink 1.0.2 Installer Zip''' link which resolves to
*Expand the zip file and get the following 2 files
===Download EclipseLink using Maven===
See the repository on
===Download EclipseLink using SVN - developers only===
*Get the following ''<font color="blue">eclipselink.jar</font>'' and ''<font color="blue">javax.persistence*.jar</font>'' from ready for your EclipseLink shared library - ''(I am running rev''
**The following page details four different ways to either obtain the binary jars or download the source and build them yourself with an anon account.
==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 off of Tomcats' lib directory, where all web applications can access it.
==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 container has a reference to the eclipselink persistence unit.
<source lang="xml">
==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)
<source lang="java">
public class FrontController extends HttpServlet implements Servlet {
  public ApplicationService applicationService = null;
  public FrontController() {
    applicationService = new ApplicationService();
<source lang="java">
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.
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'''
<source lang="java">
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import org.eclipse.persistence.internal.sessions.factories.SessionCustomizer;
import org.eclipse.persistence.sessions.JNDIConnector;
import org.eclipse.persistence.sessions.Session;
* 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
      System.out.println("_JPAEclipseLinkSessionCustomizer: configured " + connector.getName());
    } else {
      throw new Exception("_JPAEclipseLinkSessionCustomizer: Context is null");
  } catch (Exception e) {
'''<font color="red">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.</font>'''
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
<source lang="java">
<source lang="xml">
<?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 standard SE JDBC properties for the database url, username, password - I have shown a RESOURCE_LOCAL JDBC example.
<source lang="xml">
<?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        -->
    <property name="eclipselink.session.customizer" value="org.eclipse.persistence.example.unified.integration.JPAEclipseLinkSessionCustomizer"/>       
        <!-- property name="" value=""/>           
        <property name="eclipselink.jdbc.driver" value="oracle.jdbc.driver.OracleDriver"/>
        <property name="eclipselink.jdbc.url" value="jdbc:oracle:thin:@"/>
        <property name="eclipselink.jdbc.user" value="ttocs"/>
        <property name="eclipselink.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 - 1.0 (Build SNAPSHOT-20081022)
[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.
<source lang="java">
// 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===
<source lang="java">
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===
==Using JNDI outside the Tomcat container for J2SE Applications==
*<font color="red">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.</font>  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)
<source lang="xml">
<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
<source lang="xml">
<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)
<source lang="java">
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)
*See [[EclipseLink/UserGuide/Developing_JPA_Projects_%28ELUG%29|Developing JPA Projects]] in the EclipseLink User's Guide.
*Reverified JTA on 20081107
*Use this [ EclipseLink Tomcat Tutorial] as the original authored source from a [ JNDI in J2SE question in Aug 2008] for the [[EclipseLink/Examples/JPA/Tomcat_Web_Tutorial#Session_Customizer|*EclipseLinkSessionCustomer]] class that is also listed in the following tutorial.
*'''<font color="green">Original EclipseLink build 20080808 - Michael.OBrien</font>'''

Revision as of 17:23, 24 March 2009

EclipseLink JPA Deployed on Tomcat 6 using Eclipse WTP

Back to the top