Skip to main content

Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.

Jump to: navigation, search

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

m (Replacing page with '=EclipseLink JPA Deployed on Tomcat 6 using Eclipse WTP=')
m (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 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.
 +
 +
==Source==
 +
http://bugs.eclipse.org/250476
 +
 +
==Development Environment==
 +
'''Software:''' [http://phoenix.eclipse.org/packages 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 11.1.0.6.0, 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.
 +
 +
==Prerequisites==
 +
===<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 [http://wiki.eclipse.org/Dali DALI] tool.
 +
 +
===<font color="green">Install the Tomcat 6 Web Container</font>===
 +
*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===
 +
===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.''
 +
 +
See
 +
http://tomcat.apache.org/tomcat-5.5-doc/jndi-datasource-examples-howto.html#Database%20Connection%20Pool%20(DBCP)%20Configurations
 +
 +
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>.
 +
<pre>
 +
<Resource
 +
  name="jdbc/OracleDS"
 +
  auth="Container"
 +
  type="javax.sql.DataSource"
 +
  maxActive="100"
 +
  maxIdle="30"
 +
  maxWait="10000"
 +
  username="ttocs"
 +
  password="password"
 +
  driverClassName="oracle.jdbc.driver.OracleDriver"
 +
  url="jdbc:oracle:thin:@127.0.0.1:1521:orcl"
 +
  />
 +
</pre>
 +
*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.
 +
<pre>
 +
<Host...>
 +
<Context
 +
  className="org.apache.catalina.core.StandardContext"
 +
  cachingAllowed="true"
 +
  charsetMapperClass="org.apache.catalina.util.CharsetMapper"
 +
  cookies="true" crossContext="false" debug="0"
 +
  displayName="unified"
 +
  docBase="C:\opt\tomcat6\webapps\unified.war"
 +
  mapperClass="org.apache.catalina.core.StandardContextMapper"
 +
  path="/unified" privileged="false" reloadable="false"
 +
  swallowOutput="false" useNaming="true"
 +
  wrapperClass="org.apache.catalina.core.StandardWrapper">
 +
  <ResourceLink
 +
    global="jdbc/OracleDS"
 +
    name="ds/OracleDS"
 +
    type="javax.sql.DataSource"/>
 +
</Context>
 +
</pre>
 +
 +
==Downloading EclipseLink Libraries==
 +
===Download EclipseLink using HTTP - recommended===
 +
*Proceed to the following URL and download the latest eclipselink.zip which contains everything you need.
 +
**http://www.eclipse.org/eclipselink/downloads/index.php
 +
***'''Click on the "EclipseLink Installer Zip''' link which resolves to http://www.eclipse.org/downloads/download.php?file=/rt/eclipselink/releases/n.n.n/eclipselink-n.n.n.zip
 +
*Expand the zip file and get the following 2 files
 +
**eclipselink-*\eclipselink\jlib\eclipselink.jar
 +
**eclipselink-*\eclipselink\jlib\jpa\javax.persistence_*.jar
 +
===Download EclipseLink using Maven===
 +
See the repository on http://www.eclipse.org/eclipselink/downloads/index.php
 +
===Download EclipseLink using SVN - developers only===
 +
*Get the following ''<font color="blue">eclipselink.jar</font>'' and ''<font color="blue">javax.persistence*.jar</font>'' from http://www.eclipselink.org ready for your EclipseLink shared library.
 +
**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.
 +
**http://wiki.eclipse.org/EclipseLink/Source
 +
 +
==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-context-ref>
 +
  <persistence-context-ref-name>persistence/em</persistence-context-ref-name>
 +
  <persistence-unit-name>statCreateTablesJTA</persistence-unit-name>
 +
  </persistence-context-ref> 
 +
</source>
 +
 +
==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() {
 +
    super();
 +
    applicationService = new ApplicationService();
 +
</source>
 +
 +
<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();
 +
  }
 +
</source>
 +
 +
==Session Customizer==
 +
Any application server that is based on the Tomcat servlet container like [http://wiki.eclipse.org/EclipseLink/Examples/JPA/JBoss_Web_Tutorial JBoss], Geronimo (defaults to Jetty but includes Tomcat as a secondary web container), WebSphere CE (based on Geronimo) and [http://wiki.eclipse.org/EclipseLink/Examples/JPA/GlassFishV2_Web_Tutorial 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
 +
* http://wiki.eclipse.org/Customizing_the_EclipseLink_Application_(ELUG)
 +
* 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
 +
      // Change from COMPOSITE_NAME_LOOKUP to STRING_LOOKUP
 +
      // 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
 +
      connector.setLookupType(JNDIConnector.STRING_LOOKUP);
 +
      System.out.println("_JPAEclipseLinkSessionCustomizer: configured " + connector.getName());
 +
    } else {
 +
      throw new Exception("_JPAEclipseLinkSessionCustomizer: Context is null");
 +
  } catch (Exception e) {
 +
    e.printStackTrace();
 +
  }
 +
  }
 +
}
 +
</source>
 +
 +
==persistence.xml==
 +
'''<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">
 +
  getEntityManager().getTransaction().begin();
 +
  getEntityManager().persist(aPackage);
 +
  getEntityManager().getTransaction().commit();
 +
</source>
 +
 +
<source lang="xml">
 +
<?xml version="1.0" encoding="UTF-8"?>
 +
<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="statCreateTablesJTA" transaction-type="JTA">
 +
  <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
 +
  <jta-data-source>java:comp/env/ds/OracleDS</jta-data-source>
 +
  <class>org.eclipse.persistence.example.unified.business.StatClass</class>
 +
  <!--.....list all entities        -->
 +
  <class>org.eclipse.persistence.example.unified.business.StatPackage</class>
 +
  <properties>
 +
    <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"/-->
 +
  </properties>
 +
</persistence-unit>
 +
</source>
 +
 +
===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="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="statCreateTablesJTA" transaction-type="RESOURCE_LOCAL">
 +
  <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
 +
  <class>org.eclipse.persistence.example.unified.business.StatClass</class>
 +
  <!--.....list all entities        -->
 +
  <class>org.eclipse.persistence.example.unified.business.StatPackage</class>
 +
  <properties>
 +
    <property name="eclipselink.session.customizer" value="org.eclipse.persistence.example.unified.integration.JPAEclipseLinkSessionCustomizer"/>       
 +
        <!-- property name="eclipselink.target-database" value="org.eclipse.persistence.platform.database.oracle.OraclePlatform"/>           
 +
        <property name="eclipselink.jdbc.driver" value="oracle.jdbc.driver.OracleDriver"/>
 +
        <property name="eclipselink.jdbc.url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"/>
 +
        <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"/-->
 +
  </properties>
 +
</persistence-unit>
 +
</source>
 +
 +
==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.
 +
 +
<pre>
 +
 +
[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(
 +
platform=>Oracle10Platform
 +
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
 +
</pre>
 +
 +
==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">
 +
getEntityManager().getTransaction().begin();
 +
getEntityManager().persist(aLabel);
 +
getEntityManager().persist(aPackage);
 +
// 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/>");
 +
getEntityManager().getTransaction().commit();
 +
</source>
 +
 +
<pre>
 +
 +
[EL Finest]: 2008.11.07 15:04:33.046--UnitOfWork(23761956)--Thread(Thread[http-8080-1,5,main])--PERSIST operation called on: org.eclipse.persistence.example.unified.business.StatLabel@7787a5.
 +
[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
 +
 +
 +
</pre>
 +
 +
===Query for Objects===
 +
<source lang="java">
 +
aQuery = entityManager.createQuery("select object(e) from StatLabel e");
 +
aResultsList = aQuery.getResultList();
 +
</source>
 +
 +
<pre>
 +
[EL Finest]: 2008.11.07 15:04:33.609--UnitOfWork(23761956)--Thread(Thread[http-8080-1,5,main])--Register the existing object org.eclipse.persistence.example.unified.business.StatLabel@39ea58
 +
</pre>
 +
 +
===Browser Output===
 +
 +
<pre>http://127.0.0.1:8080/unified/FrontController?action=demo</pre>
 +
 +
[[Image:Tomcat_eclipselink_jpa_demo_cap.JPG]]
 +
 +
==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"-->
 +
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
 +
<!-- jta-data-source>java:/comp/env/ds/OracleDS</jta-data-source-->
 +
<non-jta-data-source>java:/comp/env/ds/OracleDS</non-jta-data-source>
 +
<class>org.eclipse....list all entities</class>
 +
<properties>
 +
  <property name="eclipselink.logging.level" value="FINEST"/>           
 +
</properties>
 +
</persistence-unit>
 +
</source>
 +
 +
*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"/>
 +
</source>
 +
 +
===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)
 +
 +
http://blogs.sun.com/randystuph/entry/injecting_jndi_datasources_for_junit
 +
 +
<source lang="java">
 +
public void configureDataSource()  {
 +
Context aContext = null;
 +
// Randy Carver START
 +
try {
 +
  System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
 +
  System.setProperty(Context.URL_PKG_PREFIXES,  "org.apache.naming");           
 +
  InitialContext ic = new InitialContext();
 +
  ic.createSubcontext("java:");
 +
  ic.createSubcontext("java:/comp");
 +
  ic.createSubcontext("java:/comp/env");
 +
  ic.createSubcontext("java:/comp/env/ds");
 +
         
 +
  OracleConnectionPoolDataSource ds = new OracleConnectionPoolDataSource();
 +
  ds.setURL("jdbc:oracle:thin:@127.0.0.1:1521:orcl");
 +
  ds.setUser("ttocs");
 +
  ds.setPassword("password");
 +
  // 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
 +
  e.printStackTrace();
 +
}
 +
// 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) {
 +
      aConnection.close();
 +
    }
 +
  }
 +
} catch (Exception e) { 
 +
  try {
 +
  if(null != aContext) {
 +
    aContext.close();
 +
  }
 +
  } catch (Exception e2) {   
 +
  e2.printStackTrace();
 +
  } 
 +
  e.printStackTrace(); 
 +
}
 +
 +
}
 +
</source>
 +
 +
===Output===
 +
<pre>
 +
  >> Local DataSource Connection: oracle.jdbc.pool.OracleConnectionPoolDataSource@15b0afd
 +
</pre>
 +
 +
*Start tomcat (so we can connect via JNDI)
 +
*Run your SE app (outside the web container)
 +
 +
==References==
 +
*See [[EclipseLink/UserGuide/Developing_JPA_Projects_%28ELUG%29|Developing JPA Projects]] in the EclipseLink User's Guide.
 +
*Reverified JTA on 20081107
 +
*Use this [http://wiki.eclipse.org/EclipseLink/Examples/JPA/Tomcat_Web_Tutorial EclipseLink Tomcat Tutorial] as the original authored source from a [http://forums.oracle.com/forums/thread.jspa?threadID=519351&tstart=60 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.
 +
**http://weblogs.java.net/blog/lancea/archive/2008/11/moving_tomcat_t_1.html
 +
 +
*'''<font color="green">Original EclipseLink build 20080808 - Michael.OBrien</font>'''

Revision as of 19:35, 24 March 2009

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.

Source

http://bugs.eclipse.org/250476

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 11.1.0.6.0, 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.

Prerequisites

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

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.

See http://tomcat.apache.org/tomcat-5.5-doc/jndi-datasource-examples-howto.html#Database%20Connection%20Pool%20(DBCP)%20Configurations

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>.

 <Resource 
  name="jdbc/OracleDS" 
  auth="Container" 
  type="javax.sql.DataSource" 
  maxActive="100" 
  maxIdle="30" 
  maxWait="10000"
  username="ttocs" 
  password="password" 
  driverClassName="oracle.jdbc.driver.OracleDriver" 
  url="jdbc:oracle:thin:@127.0.0.1:1521:orcl"
  />
  • 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.

<Host...>
 <Context 
  className="org.apache.catalina.core.StandardContext"
  cachingAllowed="true"
  charsetMapperClass="org.apache.catalina.util.CharsetMapper"
  cookies="true" crossContext="false" debug="0"
  displayName="unified"
  docBase="C:\opt\tomcat6\webapps\unified.war"
  mapperClass="org.apache.catalina.core.StandardContextMapper"
  path="/unified" privileged="false" reloadable="false"
  swallowOutput="false" useNaming="true"
  wrapperClass="org.apache.catalina.core.StandardWrapper">
   <ResourceLink 
    global="jdbc/OracleDS" 
    name="ds/OracleDS"
    type="javax.sql.DataSource"/>
 </Context>

Downloading EclipseLink Libraries

Download EclipseLink using HTTP - recommended

Download EclipseLink using Maven

See the repository on http://www.eclipse.org/eclipselink/downloads/index.php

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 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.

 <persistence-context-ref>
   <persistence-context-ref-name>persistence/em</persistence-context-ref-name>
   <persistence-unit-name>statCreateTablesJTA</persistence-unit-name>
  </persistence-context-ref>

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() {
    super();
    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.

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

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
 * http://wiki.eclipse.org/Customizing_the_EclipseLink_Application_(ELUG)
 * 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
      // Change from COMPOSITE_NAME_LOOKUP to STRING_LOOKUP
      // 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
      connector.setLookupType(JNDIConnector.STRING_LOOKUP);
      System.out.println("_JPAEclipseLinkSessionCustomizer: configured " + connector.getName());
    } else {
      throw new Exception("_JPAEclipseLinkSessionCustomizer: Context is null");
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
}

persistence.xml

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
  getEntityManager().getTransaction().begin();
  getEntityManager().persist(aPackage);
  getEntityManager().getTransaction().commit();
<?xml version="1.0" encoding="UTF-8"?>
<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="statCreateTablesJTA" transaction-type="JTA">
  <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
   <jta-data-source>java:comp/env/ds/OracleDS</jta-data-source>
   <class>org.eclipse.persistence.example.unified.business.StatClass</class>
   <!--.....list all entities         -->
   <class>org.eclipse.persistence.example.unified.business.StatPackage</class>
   <properties>
    <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"/-->
   </properties>
 </persistence-unit>

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.
<?xml version="1.0" encoding="UTF-8"?>
<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="statCreateTablesJTA" transaction-type="RESOURCE_LOCAL">
  <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
   <class>org.eclipse.persistence.example.unified.business.StatClass</class>
   <!--.....list all entities         -->
   <class>org.eclipse.persistence.example.unified.business.StatPackage</class>
   <properties>
    <property name="eclipselink.session.customizer" value="org.eclipse.persistence.example.unified.integration.JPAEclipseLinkSessionCustomizer"/>        
        <!-- property name="eclipselink.target-database" value="org.eclipse.persistence.platform.database.oracle.OraclePlatform"/>            
        <property name="eclipselink.jdbc.driver" value="oracle.jdbc.driver.OracleDriver"/>
        <property name="eclipselink.jdbc.url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"/>
        <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"/-->
   </properties>
 </persistence-unit>

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(
	platform=>Oracle10Platform
	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.

 getEntityManager().getTransaction().begin();
 getEntityManager().persist(aLabel);
 getEntityManager().persist(aPackage);
 // 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/>");
 getEntityManager().getTransaction().commit();

[EL Finest]: 2008.11.07 15:04:33.046--UnitOfWork(23761956)--Thread(Thread[http-8080-1,5,main])--PERSIST operation called on: org.eclipse.persistence.example.unified.business.StatLabel@7787a5.
[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 org.eclipse.persistence.example.unified.business.StatLabel@39ea58

Browser Output

http://127.0.0.1:8080/unified/FrontController?action=demo

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"-->
 <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
 <!-- jta-data-source>java:/comp/env/ds/OracleDS</jta-data-source-->
 <non-jta-data-source>java:/comp/env/ds/OracleDS</non-jta-data-source>
 <class>org.eclipse....list all entities</class>
 <properties>
  <property name="eclipselink.logging.level" value="FINEST"/>            
 </properties>
</persistence-unit>
  • 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)

http://blogs.sun.com/randystuph/entry/injecting_jndi_datasources_for_junit

public void configureDataSource()  {
 Context aContext = null;
 // Randy Carver START
 try {
  System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
  System.setProperty(Context.URL_PKG_PREFIXES,  "org.apache.naming");            
  InitialContext ic = new InitialContext();
  ic.createSubcontext("java:");
  ic.createSubcontext("java:/comp");
  ic.createSubcontext("java:/comp/env");
  ic.createSubcontext("java:/comp/env/ds");
 
  OracleConnectionPoolDataSource ds = new OracleConnectionPoolDataSource();
  ds.setURL("jdbc:oracle:thin:@127.0.0.1:1521:orcl");
  ds.setUser("ttocs");
  ds.setPassword("password");
  // 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
  e.printStackTrace();
 }
 // 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) {
      aConnection.close();
    }
  }
 } catch (Exception e) {   
  try {
   if(null != aContext) {
    aContext.close();
   }
  } catch (Exception e2) {    
   e2.printStackTrace(); 
  }  
  e.printStackTrace();  
 }
 
}

Output

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

References

  • Original EclipseLink build 20080808 - Michael.OBrien

Back to the top