Exclude Fields in JPA With XML Mappings: Quick Guide
When you generate entity classes from XML schemas using xjc
, editing the source code breaks regeneration workflows. You can still persist the objects with JPA and mark unwanted elements as transient directly in the XML mapping file.
Workflow
- Generate an XML schema with Trang if you only have sample documents.
- Create Java bindings with
xjc
. - Define an external JPA mapping file (
META-INF/orm.xml
) referencing the generated classes.
Mapping Example
<entity class="com.domain.xml_1_0.Site" access="FIELD">
<attributes>
<transient name="siteInternalId"/>
<transient name="siteLinkage"/>
<id name="siteId"/>
</attributes>
</entity>
By declaring the fields as <transient/>
, JPA ignores them without modifying the generated code.
Tips
- Keep the mapping file under version control alongside the schema so regeneration remains deterministic.
- Use Bean Validation annotations in the mapping file if you need to enforce constraints on generated fields.
- Consider MapStruct or custom mappers to translate JAXB objects into domain models when business logic diverges from the XML structure.