JPA 2.0: Adding entity classes to PersistenceUnit *from different jar* automatically

前端 未结 8 531
余生分开走
余生分开走 2020-11-29 02:23

I have a maven-built CDI-based Java SE app, which has a core module, and other modules.
Core has the persistence.xml and some entities. Modules hav

相关标签:
8条回答
  • 2020-11-29 03:05

    Possible duplicate, see my SO question.

    We faced the same problem and the only way we found was to accumulate all entities in one persistence.xml for the final (web-)application.

    At the same time we define separate persistence.xml files in our test resources so we can run acceptance tests per module.

    0 讨论(0)
  • 2020-11-29 03:06

    I have a slightly different setup where I am placing persistence.xml in the WAR file but some of its dependencies includes @Entity annotated classed to include in the persistence unit.

    I have solved my problem using Maven a bit like Adrian Shum described in #3, but using the element to include the jars to be scanned for @Entity annotations.

    I added a property to my-web/pom.xml for each dependency including extra entities. All my jars are part of a Maven multiproject build so for me it looks like.

    <properties>
        <common.jar>common-${project.version}.jar</common.jar>
        <foo.jar>foo-${project.version}.jar</foo.jar>
    </properties>
    

    I thereafter add the following to the persistence.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <persistence version="2.0" ... >
        <persistence-unit name="primary">
            <jta-data-source>java:jboss/datasources/mysource</jta-data-source>
    
            <jar-file>lib/${common.jar}</jar-file>
            <jar-file>lib/${foo.jar}</jar-file>
    
            ...
        </persistence-unit>
    </persistence>
    

    Lastly I configure the maven-resource-plugin in web/pom.xml to replace the $expressions in persistence.xml with the properties set in the POM

    <build>
      <resources>
        <resource>
          <directory>src/main/resources</directory>
          <filtering>true</filtering>
          <includes>
            <include>**/persistence.xml</include>
          </includes>
        </resource>
        <resource>
          <directory>src/main/resources</directory>
          <filtering>false</filtering>
          <excludes>
            <exclude>**/persistence.xml</exclude>
          </excludes>
        </resource>
      </resources>
      ...
    </build>
    
    0 讨论(0)
提交回复
热议问题