user1631147
user1631147

Reputation:

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 ?

Upvotes: 1

Views: 3664

Answers (3)

timomeinen
timomeinen

Reputation: 3320

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

Upvotes: 1

James
James

Reputation: 18379

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

Upvotes: 2

Sai Ye Yan Naing Aye
Sai Ye Yan Naing Aye

Reputation: 6740

Change your fetch attributes fetch = LAZY to fetch=FetchType.LAZY from both entities likes this;

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

Upvotes: 0

Related Questions