传统上,我们尽量避免 LazyInitializationException
使用s。但是,我需要暂时允许它们被抛出。这是我正在尝试做的伪代码:
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);
该magicallySerializeDataCurrentlyInMemory
方法递归地尝试序列化内存中的数据customer
及其相关实体,LazyInitializationException
并在此过程中吸收 s。
尝试#1:session.disconnect
/session.reconnect
在这次尝试中,我使用了这种模式:
Connection connection = session.disconnect();
magicallySerializeDataCurrentlyInMemory(customer);
session.reconnect(connection);
不幸的是,它没有抛出LazyInitializationException
s。
尝试#2:session.close
/session.reconnect
在这次尝试中,我使用了这种模式:
Connection connection = session.close();
magicallySerializeDataCurrentlyInMemory(customer);
session.reconnect(connection);
不幸的是,这使得session
after 无用session.reconnect(connection)
。
我怎样才能暂时强制LazyInitializationException
s?