Persisting 3rd party objects with JPA

匿名 (未验证) 提交于 2019-12-03 02:52:02

问题:

In my current project I am using a 3rd party library which has no JPA annotations.

How can I persist objects from that library using JPA and external mappings?

回答1:

Check this and this. In short:

  1. Create META-INF/orm.xml
  2. Follow (read) the .xsd

You don't have to manually map each column - only some specifics (i.e. collections and the id) are required. All fields are assumed to be columns (if the class is mapped). If there are no collections, something like this suffices:

<?xml version="1.0" encoding="UTF-8" ?> <entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm      http://java.sun.com/xml/ns/persistence/orm_1_0.xsd"     version="1.0">      <description>External entities from library X</description>     <package>com.external.library</package>     <entity class="SomeClassName">       <id>..</id>     </entity>     <entity class="AnotherClassName">       <id>..</id>     </entity> </entity-mapping> 

Note that when specifying <package> you don't need fully-qualified names.

In case you want a file named differently than orm.xml, in your persistence.xml specify it via:

<mapping-file>customMappingFile.xml</mapping-file> 


回答2:

Refer to the docs of your JPA implementation; any serious JPA implementation should provide examples of use of XML as well as annotations. See http://www.datanucleus.org/products/accessplatform_2_0/jpa/metadata_xml.html for DataNucleus docs for XML structure, and then refer to the particular relation types for examples of different features.



回答3:

As pointed out, you can use JPA mapping file instead of annotations to map, well, non annotated entities (e.g. classes from a third party library). Follow any JPA tutorial based on mapping files to get started.

Regarding automation, I don't think you can automate the generation of orm.xml from the object model (as opposed to a physical model, an object model doesn't contain enough information, for example which field is the PK or, for a bi-directional association, which side is the owner, etc hence the need for metadata). But most IDEs provide support for this, e.g. Eclipse.



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