EclipseLink, EntityManager with two persistence units needed

て烟熏妆下的殇ゞ 提交于 2020-01-01 16:58:29

问题


I have one jar library A (or project in eclipse), which has it's own persistence unit (META-INF/persistence.xml) and some entity classes, and another project (B) using this one. In project B there is also persistence unit and entity classes.

In project B I need to use both entity classes from project A and B. But if I set "A" as persistence unit name, EntityManager cannot create named query if this query is in entity from project B. If I set "B" as persistence unit name, it cannot create named queries from entities from project A. Error message is:

NamedQuery of name: MyEntityName.myQueryName not found.

Can persistence units somehow include other persistence units? Or is there any other way to solve this problem?


回答1:


EclipseLink 2.3 introduced Composite Persistence Units, which allows you to create a persistence unit that essentially acts only as a container for two or more actual persistence units. You are then able to use this single composite persistence unit in your application as if you had only one persistence unit. This should meet your goals of keeping your persistence.xml files clean for easy synchronization of your model to database. Pretty cool stuff.




回答2:


You can list your classes needed by A in one persistence unit, and classes needed you B in an other:

<persistence ...>
    <persistence-unit name="projectA" ...>
        ....
        <class>a.Class1</class>
        <class>a.Class2</class>
        <class>a.Class3</class>
    </persistence-unit>

    <persistence-unit name="projectB" ...>
        ...
        <class>a.Class1</class>
        <class>a.Class2</class>
        <class>a.Class3</class>
        <class>b.Class1</class>
        <class>b.Class2</class>
        <class>b.Class3</class>
    </persistence-unit>
</persistence>

Alternatively, you can use the <jar-file> element, quoting from the JPA spec (6.2.1.6): "If specified, these JAR files will be searched for managed persistence classes, and any mapping metadata annotations found on them will be processed, or they will be mapped using the mapping annotation defaults defined by this specification. Such JAR files are specified relative to the root of the persistence unit (e.g., utils/myUtils.jar)."

<persistence ...>
    <persistence-unit name="projectA" ...>
        ...
        <jar-file>relative/path/to/your/library.jar</jar-file>
    </persistence-unit>
</persistence>


来源:https://stackoverflow.com/questions/1742338/eclipselink-entitymanager-with-two-persistence-units-needed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!