简体   繁体   English

在EclipseLink中分离实体

[英]Detaching Entities in EclipseLink

I have an issue with detaching entities in JPA 2.1 EclipseLink. 我在JPA 2.1 EclipseLink中分离实体时遇到问题。

I have a JavaEE application with a some entities that have all relationships set to lazy loading. 我有一个JavaEE应用程序,其中某些实体的所有关系都设置为延迟加载。 I use join fetch in all my database queries in order to fetch only the objects I need. 我在所有数据库查询中都使用了join fetch,以便仅获取所需的对象。 I use Jackson (FasterXml) for converting objects to JSON (for JAX-RS, etc.) 我使用Jackson(FasterXml)将对象转换为JSON(用于JAX-RS等)

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). 每当我从数据库中选择任何实体时,我都会在返回该实体之前分离该实体,以避免当Jackson将对象转换为JSON时在数据库上运行太多查询(因为此转换将调用要转换的实体中的所有getter)。

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. 我的问题是分离不起作用,当我查看JPA日志时,我看到该实体的所有成员都已转换并由查询加载到数据库中。 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. 当Jackson将对象转换为JSON时会发生这种情况,而我的猜测是,因为Jackson在转换对象时调用了吸气剂。 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. 认为EclipseLink的分离仅用于停止跟踪更改,出于性能原因将其从EM中撤出。 Accessing an unfetched attribute, according to the JPA spec results in an exception; 根据JPA规范访问未提取的属性会导致异常; 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. 这将需要修改EclipseLink通过编织生成的增强型Java代码,以访问惰性属性。

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. 构造函数查询而不是返回托管实体对象,而是将选择值传递给java构造函数,因此仅包括在查询中获取的数据。 These objects are not entities, and so are completely detached, and any java object can be built, even existing Entity classes. 这些对象不是实体,因此是完全分离的,并且可以构建任何java对象,甚至是现有的Entity类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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