简体   繁体   中英

JPA / EclipseLink lazy collections not loading

I have a User entity with this mapping:

@OneToMany(mappedBy = "supervisor", fetch = LAZY, cascade = [CascadeType.REFRESH])
List<Group> supervisedGroups = new ArrayList<Group>()

and a Group entity with this mapping:

@ManyToOne(fetch = LAZY, cascade = [CascadeType.REFRESH])
@JoinColumn(name = "supervisor")
User supervisor

I fetch a user thanks to a repository

User user = userRepository.findById(id)

The findById method is wrapped by a transaction (method is intercepted by a transaction manager advice), and the JPA unit of work lasts as long as the request last (session per view).

When I get the user, I do a

user.getSupervisedGroups()

This returns me an empty list. The collection type is the Eclipselinks's IndirectList and even if i call the size() method it does nothing more.

But if I execute

entitymanager.refresh(user)
user.getSupervisedGroups()

Then I have 2 items in my list... Why ? Does it means EclipseLink does not support at all LAZY fetching on collections ?

My guess is you have corrupted that objects in the shared L2 cache.

When you inserted this object, did you add the correct objects to the collection? My guess is you have a bidirectional OneToMany/ManyToOne relationship and when inserting the One side and not adding to the Many side. You must maintain your object's relationships correctly.

See, http://en.wikibooks.org/wiki/Java_Persistence/Relationships#Object_corruption.2C_one_side_of_the_relationship_is_not_updated_after_updating_the_other_side

将你的获取属性fetch = LAZY更改为fetch =来自两个实体的FetchType.LAZY都喜欢这个;

  @OneToMany(mappedBy = "supervisor", fetch=FetchType.LAZY, cascade = CascadeType.REFRESH)

The answer by James might be the origin of the problem. Another solution is to disable EclipseLinks L2 cache:

Persistence Unit property:

<property name="eclipselink.cache.shared.default" value="false"/>

Or JPA 2.0 persistence unit element:

<shared-cache-mode>NONE</shared-cache-mode>

Source: https://wiki.eclipse.org/EclipseLink/FAQ/How_to_disable_the_shared_cache%3F

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