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.
Try using the jta-data-source
element in your persistence.xml.
<jta-data-source>java:comp/env/jdbc/FooBarDataSourceJNDI</jta-data-source>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With