0

传统上,我们尽量避免 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);

不幸的是,它没有抛出LazyInitializationExceptions。

尝试#2:session.close/session.reconnect

在这次尝试中,我使用了这种模式:

Connection connection = session.close();

magicallySerializeDataCurrentlyInMemory(customer);

session.reconnect(connection);

不幸的是,这使得sessionafter 无用session.reconnect(connection)

我怎样才能暂时强制LazyInitializationExceptions?

4

1 回答 1

1

没有办法暂时关闭会话。您可以做的是从会话中删除实体,然后将其放回原处。

session.evict(customer);
//do something will throw lazy load
session.refresh(customer);

连接和重新连接只是手动管理正在使用的特定 JDBC 连接。hibernate Session 是一个比单个 JDBC 连接更大的概念。连接只是它的一种资源。它可以在其整个生命周期中使用许多不同的物理数据库连接,并且一点也不关心。如果您断开连接,然后要求 Session 做某事,它将获得另一个连接。

于 2012-04-03T18:34:24.970 回答