I'm starting a new project that's using both JAXB and JPA annotations. I've read with interest the posts discussing the pros and cons of mixing both JAXB and JPA annotations in a single class.
Are there any guidelines describing when to use field level annotations and when to use property level annotations, or any arguments for generally choosing one approach over the other? I find field level annotations cleaner and more readable; they're usually found at the top of the class and make it easy to figure out how each field is represented in varying contexts. Aside from this argument concerning readability however, are there any other things to consider when deciding where to annotate?
JAXB simplifies access to an XML document from a Java program by presenting the XML document to the program in a Java format. The first step in this process is to bind the schema for the XML document into a set of Java classes that represents the schema.
JAXB was integrated within the JVM itself, so you didn't need to add any code dependency to have the functionality within your application. But with the modularization performed in JDK 9, it was removed as the maintainers wanted to have a smaller JDK distribution that only contains the core concepts.
With Java releases lower than Java 11, JAXB was part of the JVM and you could use it directly without defining additional libaries. As of Java 11, JAXB is not part of the JRE anymore and you need to configure the relevant libraries via your dependency management system, for example Maven or Gradle.
The JAXB-specific xjc and schemagen tools, which you use to convert an XML Schema (*. xsd file) to a set of Java classes and vice versa, are included with the JDK up to version 10, but have been removed in JDK 11.
JPA often uses lazy loading on properties. If you use property access in JAXB then it will trigger these lazy properties during a marshal.
Also in order to support lazy loading (or change tracking, etc). Some JPA implementations use byte code manipulation to introduce fields onto classes to enable this. Using field access with JAXB can cause errors when using this type of JPA implementation.
Some reference material related to using JAXB with JPA entities:
Another advantage is, that you don't have to expose all fields as properties. If there is not a good reason to do otherwise I generally prefer field level annotations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With