gpt4 book ai didi

java - "proxied"状态对于 Hibernate session 意味着什么

转载 作者:太空宇宙 更新时间:2023-11-04 06:14:57 25 4
gpt4 key购买 nike

我在 Jboss 站点上看到了有关 Hibernate 文档的这一行。

Because Hibernate can't bind the "current session" to a transaction, 
as it does in a JTA environment, it binds it to the current Java thread
when i do transction demarcation with plain JDBC.
It is opened when getCurrentSession() is called for the first time,
but in a "proxied" state that doesn't allow you to do anything except
start a transaction.

那么,作者在这里所说的“代理状态”到底是什么意思?它们与代理对象有什么联系(如果有的话)?

最佳答案

如果没有 JTA,事务管理是通过 JDBC Connection 的提交/回滚方法完成的。 .

这意味着您必须将一个 JDBC 连接绑定(bind)到当前正在运行的 Hibernate session 和当前逻辑事务。

因为将 JDBC 连接传递给所有 Hibernate Session 方法将是一个糟糕的设计解决方案,所以您必须使用线程本地存储。

Hibernate 有一个灵活的 CurrentSessionContext ,提供以下替代方案:

  • JTASessionContext
  • 托管 session 上下文
  • ThreadLocalSessionContext

因此,如果您选择 ThreadLocaSessionContext,那么底层 JDBC 连接将绑定(bind)到 Thread 本地存储,并使其可供当前线程运行的 Session 使用。

如果您使用 Spring,则不应依赖 Hibernate TreadLocal 上下文,而应使用 Spring 特定的事务管理支持,该支持是通过以下方式实现的:

  • SpringJtaSessionContext
  • SpringSessionContext

对于代理状态,Hibernate TreadLocalContext 使用 Hibernate Session 的代理:

protected Session wrap(Session session) {
final TransactionProtectionWrapper wrapper = new TransactionProtectionWrapper( session );
final Session wrapped = (Session) Proxy.newProxyInstance(
Session.class.getClassLoader(),
SESSION_PROXY_INTERFACES,
wrapper
);
wrapper.setWrapped( wrapped );
return wrapped;
}

当调用 Session.close() 方法时,允许当前 Session 从 TreadLocal 存储中解除绑定(bind)

// If close() is called, guarantee unbind()
if ( "close".equals( methodName ) ) {
unbind( realSession.getSessionFactory() );
}

关于java - "proxied"状态对于 Hibernate session 意味着什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28209309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com