问题
I'm working with JBoss. i created a simple JAX-RS Webservice that retrieves a JPA Entitiy from the database and returns it to the user. As soon as I have a relationship (@OneToOne) to another Entity I get a LazyInitializationException. The Reason is simple: The Relationship was not initialized by JPA (lazy loading) and when jaxb tries to serialize it, everything breaks.
But how do i solve this?
I could touch the relationship before i return the object. Not nice and complex for greater object networks.
I could extend my Persistence context, so my session is still active during jaxb serialization. Great idea, but how?
Is there a standart, best practice way to solve my problem.
Laures
回答1:
You will need to ensure you are annotation the properties (accessors) and not the fields (instance variables), when dealing with JPA entities.
Below is an example of creating a JAX-RS service with JAX-RS, JAXB, and JPA:
- Part 1 - The Database
- Part 2 - Mapping the Database to JPA Entities
- Part 3 - Mapping JPA entities to XML (using JAXB)
- Part 4 - The RESTful Service
- Part 5 - The Client
回答2:
You have to use @XmlTransient
annotation to prevent the relationship from being serialized.
回答3:
You could change the relationship annotation to eagerly fetch the object.
@OneToOne(fetch=FetchType.EAGER)
来源:https://stackoverflow.com/questions/5990005/jpa-lazyinitializationexception-when-returning-a-jaxb-object-through-a-webservic