You can perfectly use JPA in a standalone client application with a main()
class as entry point. Just add the JPA JAR(s) to the buildpath/classpath and configure the persistence.xml
to use a RESOURCE_LOCAL
transaction type. You can find kickoff examples in EclipseLink Wiki - Running JPA Outside Container. Here's an extract of relevance:
<persistence-unit name="LocalPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
<property name="javax.persistence.jdbc.user" value="scott"/>
<property name="javax.persistence.jdbc.password" value="tiger"/>
</properties>
</persistence-unit>
You can reuse the client project with JPA models and eventual DAOs in the web project by adding the client project as a module of the web project. On Eclipse for example, you just have to add the client project to the buildpath of the web project by Java Build Path > Projects > Add and configure the Deployment Assembly to let it end up as JAR in /WEB-INF/lib
.
Finally, in your web project you can have another persistence.xml
which basically points the JAR file of the client project and overriddes the transaction type.
<persistence-unit name="WebPersistenceUnit" transaction-type="JTA">
<jta-data-source>jdbc/DataSourceName</jta-data-source>
<jar-file>lib/JavaProject.jar</jar-file>
</persistence-unit>
This way you don't need to repeat the model classes in persistence.xml
.