Search code examples
javaspringhibernatespring-data-jpaspring-data

How to unload Relationship collection in spring data?


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?


Solution

  • 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));