The purpose of this blog post is to help a user we were assisting on Twitter who wanted to use JAXB to marshal JPA entities into XML but only wanted a portion of the entities to be used. By default JAXB will traverse all available relationships including lazy ones that have not been loaded to build a complete XML document for the provided entities.
Here is a simple example reading a Customer with an Address (1:1) and PhoneNumber(s) (1:M) from a database and marshalling it into XML using EclipseLink JPA with EclipseLink MOXy.
Setup code for JPA and JAXB:
// JPAExample: Find & Marshall Customer
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("CustomerService");
EntityManager em = emf.createEntityManager();
// JAXB
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
true);
Customer customer = em.find(Customer.class, 1);When executed this generates the following XML and causes the customer's address and phone numbers to be loaded from the database.
marshaller.marshal(customer, System.out);

Customer customer = em.find(Customer.class, (long) 1);Now the generated XML appears as:
CopyGroup cg = new CopyGroup();
cg.addAttribute("id");
cg.addAttribute("firstName");
cg.addAttribute("lastName");
cg.addAttribute("address.id");
cg.addAttribute("address.city");
cg.addAttribute("address.street");
JpaEntityManger nativeEM = em.unwrap(JpaEntityManager.class);
Customer custCopy = (Customer) nativeEM .copy(customer, cg);
marshaller.marshal(custCopy , System.out);

Doug
Additional MOXy examples available here.