首页 > 解决方案 > SpringBoot 2.3.x -> 2.4.1:不能再解开 Session 类

问题描述

升级到 Spring Boot 2.4.1 后。我现在得到一个例外

com.sun.proxy.$Proxy134 and org.hibernate.engine.spi.SessionFactoryImplementor are in unnamed module of loader 'app'
at at.myClass.core.StatusControllerBase.statusInfo(StatusControllerBase.java:89)

匹配的代码是

public class StatusControllerBase {

    @Autowired
    private EntityManager em;
    ...
    public void doSomethingWithHibernate() {
            final SessionFactoryImplementor entityManagerFactory = (SessionFactoryImplementor) em
                    .unwrap(org.hibernate.Session.class).getEntityManagerFactory();

SpringBootApplication 与 StatusControllerBase ( ) 位于不同的项目中myStatusProject。任何的想法

更新

正如 Roar S. 正确地计算出失败的演员。我需要它的主要目的是检索 JDBC 连接字符串的完整 URL。或者更准确地说,我终于对 DB 主机感兴趣了。当前工作的代码如下所示:

final Session session = em.unwrap(org.hibernate.Session.class);

final SessionFactory sessionFactory = session.getSessionFactory();

final SessionFactoryImplementor entityManagerFactory = (SessionFactoryImplementor) em
            .unwrap(org.hibernate.Session.class).getEntityManagerFactory();
final DatasourceConnectionProviderImpl connectionProvider = (DatasourceConnectionProviderImpl) entityManagerFactory
            .getServiceRegistry().getService(ConnectionProvider.class);
final String strUrl = ((HikariDataSource) connectionProvider.getDataSource()).getJdbcUrl().substring(5);
final URI uri = URI.create(strUrl);
ret.put("host", uri.getHost());

标签: spring-boot

解决方案


在与 OP 讨论后,现有代码的目的是从连接字符串中检索主机名。如果 application.properties 中存在连接字符串,更简单的方法是执行以下操作(替换spring.datasource.url为 application.properties/application.yml 中连接字符串的实际路径):

public class StatusControllerBase {

  @Autowired
  private EntityManager em;

  @Value("${spring.datasource.url}")
  private String datasourceUrl;

  ...

推荐阅读