Home > Software design >  How to unload Relationship collection in spring data?
How to unload Relationship collection in spring data?

Time:09-22

I have entity Participant

public class Participant extends AbstractParticipant
{
    ...

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "participant")
    private List<MediaCallParticipant> mediaCallParticipant = new LinkedList<>();
    
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "participant")
    private List<AudioCallParticipant> audioCallParticipant = new LinkedList<>();
}

I'm writing a test. Where I do participantRepository.findOne(...) But in the test I can't get a LazyLoadException with participant.getAudioCallParticipant() or participant.getMediaCallParticipant(). I have written code that is ready to Lazy exception. but this collections are always load in entity. Is it possible to somehow manually "unload" the collections?

CodePudding user response:

Your code is supposed to work. If you need to do this in a test, try this code

        // init here another context

        TestTransaction.start();
        participant = participantRepository.findOne(participant);
        getSessionFactory().getStatistics().clear();
        participant.getMediaCallParticipant();

        //assert
        assertThat(getStatistics().getPrepareStatementCount(),is(1L));

CodePudding user response:

Detach entity or close the session before call participant.getAudioCallParticipant() (you will get the same result).
Ths is because lazy associations cannot be fetched for the detached entities.

  • Related