Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenJpa and JNDI

Tags:

jpa

jndi

openjpa

For OpenJPA, how can I specify a JNDI connection in jta_datasource without specifying username and password in persistence.xml? It gives me an error when no username and password is specified in persistence.xml file for jndi.

like image 442
JEE_program Avatar asked Nov 03 '22 10:11

JEE_program


2 Answers

Try using the jta-data-source element in your persistence.xml.

<jta-data-source>java:comp/env/jdbc/FooBarDataSourceJNDI</jta-data-source>
like image 66
Rick Avatar answered Nov 17 '22 21:11

Rick


Great question; this isn't covered well in the OpenJPA documentation. What you need to do is use the special "java:comp/env/..." syntax for the "openjpa.ConnectionFactoryName" property to ask OpenJPA to retrieve the connection parameters from JNDI. For example, your persistence.xml should look something like this:

<?xml version="1.0"?>
<persistence>
  <persistence-unit name="openjpa">
    <provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
    <class>tutorial.Animal</class>
    <class>tutorial.Dog</class>
    <class>tutorial.Rabbit</class>
    <class>tutorial.Snake</class>
    <properties>
      <property name="openjpa.ConnectionFactoryName" value="java:comp/env/jdbc/myjndi"/>
      <property name="openjpa.Log" value="DefaultLevel=WARN, Tool=INFO"/>
    </properties>
  </persistence-unit>
</persistence>

This will request a jndi resource called "myjndi" from the container. If you're using Tomcat, you would have a context.xml that looks something like this:

<?xml version='1.0' encoding='UTF-8'?>
<Context>
    <Resource name="jdbc/myjndi"
        auth="Container"
        scope="Shareable"
        type="javax.sql.DataSource"
        maxActive="100"
        maxIdle="30"
        maxWait="10000"
        removeAbandoned="true"
        username="username"
        password="password"
        driverClassName="com.mysql.jdbc.Driver"
        url="jdbc:mysql://localhost:3306/DBNAME?characterEncoding=UTF-8"
        />
</Context>

Change the JNDI parameters above as required for your database.

like image 40
Templar Avatar answered Nov 17 '22 20:11

Templar