3

I want to use connection pool with JPA/TopLink in my web app running on tomcat.Earlier I use jdbc's Connection and Statement classes to manipulate data in database; to use connection pool in that way I simply declare resource in context.xml and get this resource in application:

Context c = new InitialContext();
DataSource source = (DataSource) ((Context)c.lookup("java:comp/env")).lookup("jdbc/MySource");

And now I want to use such connection pool with JPA. How can i do this?

One more question: I've seen in some examples that the reosurce is declared in context.xml and then it is declared in web.xml in < resource-ref>. Why I should declare it in different places or is it the same declaration, I mean is it an equivalent of declaration in context.xml?

maks
  • 5,911
  • 17
  • 79
  • 123

1 Answers1

6

And now I want to use such connection pool with JPA. How can i do this?

Assuming that you've already declared the connection pooled datasource creation by <Resource> in a context.xml, then you just need to declare the datasource usage for JPA in the webapp's /META-INF/persistence.xml.

<persistence-unit name="YourPersistenceUnit" transaction-type="JTA">
    <jta-data-source>jdbc/MySource</jta-data-source>
</persistence-unit>

One more question: I've seen in some examples that the reosurce is declared in context.xml and then it is declared in web.xml in <resource-ref>. Why I should declare it in different places or is it the same declaration, I mean is it an equivalent of declaration in context.xml?

The <Resource> one in context.xml definies the creation of the datasource by the servletcontainer. It can be used by multiple webapps. The <resource-ref> one in web.xml definies the usage of the datasource by the particular webapp. Note: when using JPA, you don't need the one in web.xml. It goes into persistence.xml.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • So, if I define < resource> in context.xml and don't define in web.xml, will I be able to use the pooled connections or it simply will create new connection each time when I fetch the data from db? – maks Jun 09 '11 at 14:37
  • The Tomcat datasource uses by default the builtin DBCP datasource which is a connection pool already. You can however change it by altering the `factory` parameter in ``, see also http://stackoverflow.com/questions/520585/connection-pooling-options-with-jdbc-dbcp-vs-c3p0/3481821#3481821 – BalusC Jun 09 '11 at 14:41
  • @BalusC How can we get Entitymanager From Datasource......because I Have heard we cant do connection pooling with JPA in tomcat since its not a JEE server and I am uisng JPA utill class from which i am getting entitymanager... :) – goodyzain Mar 23 '15 at 05:17