Multiple jars, single persistence unit solution?

限于喜欢 提交于 2019-12-03 03:13:55

问题


Some people, including me, have been struggling with merging entities from different modules (jars) into a single persistence unit (especially with JavaSE, for instance here JPA 2.0: Adding entity classes to PersistenceUnit *from different jar* automatically ). Based on the answers there is no easy direct way to do that. One of solutions is to list all classes from all jars in single persistence unit file, but that's not really elegant. I might have accidentally found another way. Generally all my entity classes are mapped using annotations. As for the solution: persistence.xml can include multiple XML mapping files, eg:

main.jar!META-INF/persistence.xml:

<persistence-unit name="PU" transaction-type="RESOURCE_LOCAL">
  <mapping-file>META-INF/order-mappings.xml</mapping-file>
  <mapping-file>META-INF/customer-mappings.xml</mapping-file>
</persistence-unit>

The mapping files can be placed in different jars. What I noticed is that they may contain <entity> elements without any attributes, eg:

order.jar!META-INF/order-mappings.xml

<entity-mappings>       
  <entity class="com.company.Order"></entity>    
</entity-mappings>

Even if the mapping file doesn't map any attributes the annotations in Java class are taken into account anyway and everything seems to work just fine! That would mean it is easily possible to include entities from multiple jars into a single persistence unit just by including XML mapping files from particular JARs.

My question is: is this an allowed JPA mapping file usage or just a side-effect of my persistence provider (Hibernate)?


回答1:


Yes, this is allowed by the JPA specification.

XML entity mappings are designed to override JPA annotations. Unless you specifically change the default behavior using <xml-mapping-metadata-complete/> tag, JPA provider will use annotations where there is no XML mapping.

Here is an excerpt from the JPA 2.0 spec:

12.1 Use of the XML Descriptor

... The absence or present of the xml-mapping-metadata-complete subelement contained in the persistence-unit-defaults subelement of the entity-mappings element controls whether the XML object/relational mapping descriptor is used to selectively override annotation values or whether it serves as a complete alternative to Java language metadata annotations.

If the xml-mapping-metadata-complete subelement is specified, the complete set of mapping metadata for the persistence unit is contained in the XML mapping files for the persistence unit, and any persistence annotations on the classes are ignored.



来源:https://stackoverflow.com/questions/15026302/multiple-jars-single-persistence-unit-solution

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