0

I have a project with model like below (pseudocode):

class Transaction{

      @OneToMany(mappedBy="transaction", fetch = FetchType.LAZY)
      private Set<TransactionVersion> transactionVersions;
}

class TransactionVersion{

      @ManyToOne(fetch = FetchType.EAGER)
      @JoinColumn(name="ID_TRANSACTION_VERSION")
      private Transaction transaction;

      @ManyToOne(fetch = FetchType.EAGER)
      @JoinColumn(name="ID_CLIENT_VERSION")
      private ClientVersion clientVersion;
  }

  class ClientVersion{

      @OneToMany(mappedBy="clientVersion",fetch=FetchType.Lazy)
      private Set<TransactionVersion> transactionVersions;

      @OneToMany(mappedBy="client", fetch=FetchType.LAZY)
      private Set<Client> clients;
  }

Now if I try to get something like this (get(0) is just an example):

  transaction.getTransactionVersions().get(0)
 .getClientVersion().getClients()

I get LazyInitializationException failed to lazily initialize a collection of role: ClientVersion.clients, no session or session was closed

If I change FetchType on relation between ClientVersion and Client to EAGER it works but I'd certainly prefer to have it loaded lazily.

I know I can initialize the collection manually if I have access to hibernate session but is there any way to map it so that Hibernate could do it by himself? I don't want to have to use my custom method when I want to get some related objects.

1 Answer 1

2

With FetchType.LAZY you load data on demand. But if you are out of scope of the session you can't load them because the session is already closed.

With FetchType.EAGER you load all data in one time executing a join in the database, so you don't have the exception, because when you are out of scope of the session the data are already loaded and you don't need to extract them from the database

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.