JPA LazyInitializationException when returning a JAXB object via Webservice

I work with JBoss. I created a simple JAX-RS Webservice that extracts a JPA Entitiy from a database and returns it to the user. As soon as I have a relationship (@OneToOne) with another object, I get a LazyInitializationException. The reason is simple: the relation was not initialized by JPA (lazy loading), and when jaxb tries to serialize it, everything breaks.

But how can I solve this?

I could touch the relationship before I return the object. Not beautiful and difficult for large networks of objects.

I could expand the Persistence context, so my session is still active during jaxb serialization. Great idea, but how?

Is there a standard, better way to solve my problem.

Laures

+4
source share
3 answers

You will need to make sure that you annotate properties (accessors), not fields (instance variables) when working with JPA objects.

The following is an example of creating a JAX-RS service with JAX-RS, JAXB, and JPA:

0
source

You should use the @XmlTransient annotation to prevent serialization of the relationship.

0
source

You can change the annotation of the relationship to look forward to the object.

 @OneToOne(fetch=FetchType.EAGER) 
0
source

Source: https://habr.com/ru/post/958697/


All Articles