druid connection holder is null 错误记录

场景

springboot
使用的是druid连接池
执行原生sql
直接注入了EntityManager
调用 createNativeQuery方法执行sql

问题

出现异常:

Caused by: java.sql.SQLException: connection holder is null
	at com.alibaba.druid.pool.DruidPooledConnection.checkStateInternal(DruidPooledConnection.java:1157)
	at com.alibaba.druid.pool.DruidPooledConnection.checkState(DruidPooledConnection.java:1148)
	at com.alibaba.druid.pool.DruidPooledConnection.prepareStatement(DruidPooledConnection.java:336)
	at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:145)
	at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:171)
	... 84 more

尝试解决

修改druid配置

        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setRemoveAbandoned(true);
        datasource.setRemoveAbandonedTimeout(60000);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        datasource.setKeepAlive(true);

失败~

恍然大悟

我是直接从spring容器中注入的EntityManager,会不会不能这么干?
所以,我尝试注入EntityManagerFactory,用它创建EntityManager,而不是直接注入EntityManager,问题解决~,具体为什么待进一步分析

进一步分析

为什么直接从spring中获取的EntityManager不能直接使用呢?
...待完成

总结

造成connection holder is null的原因有很多,我这次仅仅是其中一个,朋友们可能遇到其他的原因,希望能给大家参考

(全文完)

(转载本站文章请注明作者和出处 druid connection holder is null 错误记录