且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java EE 6框架仅用于Web应用程序还是我也可以将它用于客户端应用程序

更新时间:2023-12-03 13:46:58

你可以完美地使用JPA在独立客户端应用程序中,以 main()类作为入口点。只需将JPA JAR添加到buildpath / classpath并配置 persistence.xml 即可使用 RESOURCE_LOCAL 事务类型。您可以在 EclipseLink Wiki - 运行JPA Outside Container 中找到启动示例。以下是相关摘录:

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>

通过添加客户端项目,您可以在Web项目中重用客户端项目和JPA模型以及最终的DAO作为Web项目的一个模块。例如,在Eclipse上,您只需通过 Java构建路径>项目>添加将客户端项目添加到Web项目的构建路径,并配置部署程序集以允许它在 / WEB-INF / lib 中结束为JAR。

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.

最后,在您的Web项目中,您可以拥有另一个 persistence.xml 它基本上指向客户端项目的JAR文件并覆盖事务类型。

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>

这样您就不需要在持久性中重复模型类。 xml