开发者

Using tomcat's connection pool with JPA

开发者 https://www.devze.com 2023-03-11 08:32 出处:网络
I want to use connection pool with JPA/TopLink in my web app running on tomcat.Earlier I use j开发者_开发百科dbc\'s Connection and Statement classes to manipulate data in database; to use connection p

I want to use connection pool with JPA/TopLink in my web app running on tomcat.Earlier I use j开发者_开发百科dbc'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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号