简体   繁体   中英

Detaching Entities in EclipseLink

I have an issue with detaching entities in JPA 2.1 EclipseLink.

I have a JavaEE application with a some entities that have all relationships set to lazy loading. I use join fetch in all my database queries in order to fetch only the objects I need. I use Jackson (FasterXml) for converting objects to JSON (for JAX-RS, etc.)

Whenever I select any entity from the database, I detach that entity before returning it to avoid running too many queries on the database when Jackson converts that object to JSON, (since this conversion calls all the getters in the entity being converted).

My problem is that the detaching does not work, and when I look at the JPA logs I see that all members of the entity being converted and being loaded by a query on the database. This happens when Jackson converts the object to JSON, and my guess is that it is because Jackson calls the getters while converting the object. Why does this happen and how can I fix it?

Detach for EclipseLink was thought only to be used to stop tracking changes, pulling it out of the EM for performance reasons. Accessing an unfetched attribute, according to the JPA spec results in an exception; something that no user seemed to really request early on, so the behaviour was not implemented. If you want this behaviour, request it.

Anyone can check the fetch state of a lazy property within their accessor and throw an application exception. This would require modifying the resulting enhanced java code that EclipseLink generates with weaving to access the lazy properties.

Another solution might be to use a constructor query . Constructor queries, instead of returning managed entity objects, pass the select values to a java constructor, so only data fetched within the query are included. These objects are not entities, and so are completely detached, and any java object can be built, even existing Entity classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM