Temporarily forcing LazyInitializationExceptions
-
28-05-2021 - |
Question
Traditionally, we try to avoid LazyInitializationException
s. However, I need to temporarily allow them to be thrown. This is the pseudo code of what I'm trying to do:
Session session = ...;
Customer customer = (Customer) session.get(Customer.class, 56);
// All eagerly fetched data is now in memory.
disconnectSession(session);
// Attempts to access lazy data throw LazyInitializationExceptions.
// I want to take advantage of this fact to *only* access data that
// is currently in memory.
magicallySerializeDataCurrentlyInMemory(customer);
// Now that the in-memory data has been serialized, I want to re-connect
// the session.
reconnectSession(session);
The magicallySerializeDataCurrentlyInMemory
method recursively attempts to serialize in-memory data of customer
and its related entities, absorbing LazyInitializationException
s along the way.
Attempt #1: session.disconnect
/ session.reconnect
In this attempt, I used this pattern:
Connection connection = session.disconnect();
magicallySerializeDataCurrentlyInMemory(customer);
session.reconnect(connection);
Unfortunately, it didn't throw LazyInitializationException
s.
Attempt #2: session.close
/ session.reconnect
In this attempt, I used this pattern:
Connection connection = session.close();
magicallySerializeDataCurrentlyInMemory(customer);
session.reconnect(connection);
Unfortunately, this rendered the session
useless after session.reconnect(connection)
.
How can I temporarily force LazyInitializationException
s?
Solution
There isn't a way to temporarily close the session. What you can do is remove the Entity from the session and then put it back.
session.evict(customer);
//do something will throw lazy load
session.refresh(customer);
connect and reconnect just manually manage what particular JDBC connection is in use. A hibernate Session is a larger concept than a single JDBC connection. The connection is just a resource to it. It can go through using many different physical database connections throughout its lifecycle and not care one bit. If you disconnect then ask the Session to do something, it will just go get another connection.