本文介绍了C3P0受管连接池无法从其主要资源或工厂资源获取资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用Postgresql作为我的底层数据库,并让Spring管理我的数据源/连接池。我的配置是这样的
< bean id =clientDataSourceclass =com.mchange.v2.c3p0.ComboPooledDataSource destroy-method =close>
< property name =driverClassvalue =org.postgresql.Driver/>
< property name =jdbcUrlvalue =jdbc:postgresql:// localhost:5432 / genesis_cms/>
< property name =uservalue =user/>
< property name =passwordvalue =password/>
< / bean>
< bean id =entityManagerFactoryclass =org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean>
< property name =dataSourceref =clientDataSource/>
< property name =packagesToScanvalue =org.myproject.package.commons.model。*/>
< property name =jpaVendorAdapter>
< bean class =org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter/>
< / property>
< property name =jpaProperties>
<道具>
< prop key =hibernate.dialect> $ {hibernate.sql.dialect}< / prop>
< prop key =hibernate.connection.pool_size> $ {hibernate.connection.pool_size}< / prop>
< prop key =hibernate.format_sql> true< / prop>
< prop key =hibernate.connection.provider_class> org.hibernate.connection.C3P0ConnectionProvider< / prop>
< prop key =hibernate.connection.driver_class> org.postgresql.Driver< / prop>
< prop key =show_sql> true< / prop>
< prop key =hibernate.c3p0.min_size> 5< / prop>
< prop key =hibernate.c3p0.max_size> 15< / prop>
< prop key =hibernate.c3p0.timeout> 300< / prop>
< prop key =hibernate.c3p0.max_statements> 50< / prop>
< prop key =hibernate.c3p0.idle_test_period> 3000< / prop>
SCHEMA
org.myproj.hibernate.SchemaResolver
org.myproj.hibernate .MultitenantConnectionProvider
< / props>
< / property>
< / bean>
< bean id =transactionManagerclass =org.springframework.orm.jpa.JpaTransactionManager>
< property name =entityManagerFactoryref =entityManagerFactory/>
< / bean>
但是,无论何时启动我的应用程序,都会显示此日志消息。
初始化c3p0池... com.mchange.v2.c3p0.PoolBackedDataSource@88f0b8ea [connectionPoolDataSource - > com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@ce8fda44 [acquireIncrement - > 3,acquireRetryAttempts - > 30,acquireRetryDelay - > 1000,autoCommitOnClose - > false,automaticTestTable - > null,breakAfterAcquireFailure - > false,checkoutTimeout - > 0,connectionCustomizerClassName - > null,connectionTesterClassName - > com.mchange.v2.c3p0.impl.DefaultConnectionTester,debugUnreturnedConnectionStackTraces - > false,factoryClassLocation - > null,forceIgnoreUnresolvedTransactions - > false,identityToken - > 1hge0yw969iurgbvtwis0 | 6ee5f485,idleConnectionTestPeriod - > 3000,initialPoolSize - > 5,maxAdministrativeTaskTime - > 0,maxConnectionAge - > 0,maxIdleTime - > 300,maxIdleTimeExcessConnections - > 0,maxPoolSize - > 15,maxStatements - > 50,maxStatementsPerConnection - > 0,minPoolSize - > 5,nestedDataSource - > com.mchange.v2.c3p0.DriverManagerDataSource@ce2ef138 [描述 - > null,driverClass - > null,factoryClassLocation - > null,identityToken - > 1hge0yw969iurgbvtwis0 | ccd341d,jdbcUrl - > null,属性 - > {}],preferredTestQuery - > null,propertyCycle - > 0,statementCacheNumDeferredCloseThreads - > 0,testConnectionOnCheckin - > false,testConnectionOnCheckout - > false,unreturnedConnectionTimeout - > 0,usesTraditionalReflectiveProxies - >假; userOverrides:{}],dataSourceName - > null,factoryClassLocation - > null,identityToken - > 1hge0yw969iurgbvtwis0 | 53eba4b8,numHelperThreads - > 3]
我相信我已经正确配置了我的设置,任何想法如何调试或解决此问题?
我得到的异常。
com.mchange.v2 .resourcepool.CannotAcquireResourceException:ResourcePool无法从其主工厂或源获取资源。
at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1418)
at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:606)
在com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:526)
在com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutAndMarkConnectionInUse(C3P0PooledConnectionPool.java:755)
。在COM .mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:682)
在com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:140)
。在组织.hibernate.c3p0.internal.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:89)
在com.brightworks.genesis.client.config.hibernate.MultitenantConnectionProvider.getAnyConnection(MultitenantConnectionProvider.java:49)
。在COM .brightworks.genesis.client.config.hibernate.Mu ltitenantConnectionProvider.getConnection(MultitenantConnectionProvider.java:55)维持在org.hibernate.engine.jdbc.internal.LogicalConnectionImpl org.hibernate.internal.AbstractSessionImpl $ ContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:423)
。在org.hibernate.engine.jdbc.internal.StatementPreparerImpl处获得连接(LogicalConnectionImpl.java:228)
在org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:171)
。连接(StatementPreparerImpl.java:63)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl $ 5.doPrepare(StatementPreparerImpl.java:162)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl $ StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:186)
在org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:160)
在org.hibernate.loader.Loader.prepareQueryStateme nt(Loader.java:1884)
在org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1861)
在org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838)
在org.hibernate.loader.Loader.doQuery(Loader.java:909)
在org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
在org.hibernate .loader.loader.doList(Loader.java:2553)
在org.hibernate.loader.Loader.doList(Loader.java:2539)
在org.hibernate.loader.Loader.listIgnoreQueryCache(Loader .java:2369)
在org.hibernate.loader.Loader.list(Loader.java:2364)
在org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:496)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:231)
在org.hibernate.internal.SessionImpl.list(SessionImpl.java:1264)
在org.hibernate.internal.QueryImpl.l (org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl。))
。 Java的:495),美元,org.hibernate.jpa.criteria.compile.CriteriaQueryTypeQueryAdapter.getSingleResult(CriteriaQueryTypeQueryAdapter.java:71 b $ b)
在sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法)
。在sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
在sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
在java.lang.reflect.Method.invoke(方法。 Java的:483)
在org.springframework.orm.jpa.SharedEntityManagerCreator $ DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:360)
在com.sun.proxy $ Proxy52.getSingleResult(来源不明)$ b。 $ b at org.springframework.data.jpa.repository.query.JpaQueryExecution $ SingleEntityExecution.doExecute(JpaQueryExecution.java:197)
at org.spr ingframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:74)
在org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:97)
。在org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:88)
在org.springframework.data.repository.core.support.RepositoryFactorySupport $ QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java :421)
在org.springframework.data.repository.core.support.RepositoryFactorySupport $ QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:381)
在org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation的.java:179)
在org.springframework.data.repository.core.support.RepositoryFactorySupport $ DefaultMethodInvokingMethodInterceptor.invoke(RepositoryFactorySupport.java:512)
在org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (回覆flectiveMethodInvocation.java:179)
在org.springframework.transaction.interceptor.TransactionInterceptor $ 1.proceedWithInvocation(TransactionInterceptor.java:98)
在org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java :266)
在org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)$ b $ or $。 b $ b。在org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
在org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
。在org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor $ CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:111)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
处的com.sun org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
。 $ Proxy41.findByUsername(Unknown Source)
at org.brightworks.genesis.commons.service.account.impl.AccountServiceImpl.findByUsername(AccountServiceImpl.java:25)
at com.brightworks.genesis。客户端.webapp.controller.ProductController.addProductForm(ProductController.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62 )
在sun.reflect.DelegatingMethodAccessorImpl.invoke(Delegati ngMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:在org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132 215)
)
。在org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle( ServletInvocableHandlerMethod.java:104)
处org.springframework.web.servlet.mvc org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
。 method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
处org.springframework org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
。 web.servlet.DispatcherServlet.doDispatch(DispatcherServl (org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
在org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
在org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
在javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
在org.eclipse.jetty .servlet.ServletHolder.handle(ServletHolder.java:769)
在org.eclipse.jetty.servlet.ServletHandler $ CachedChain.doFilter(ServletHandler.java:1667)
在org.springframework.security.web .FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.s pringframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
在org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:342)
。在org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
在org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:342)
。在org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
在org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:342)
。在org.springframework.s ecurity.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)维持在org.springframework org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:342)
。 security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)维持在org.springframework org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:342)
。 security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)维持在org.springframework org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:342)
。在org.springframework.security.web.FilterChainProxy上
$ VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org。小号pringframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:342)
在org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
。在org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:342)
在org.springframework.security.web.access.channel.ChannelProcessingFilter.doFilter(ChannelProcessingFilter.java:144)
。在org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:342)
在org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
。在org.springframework.s ecurity.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
处org.springframework.web.filter org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
。 DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
at org.eclipse.jetty.servlet.ServletHandler $ CachedChain.doFilter(ServletHandler.java:1650)
at com.googlecode.webutilities.filters.CompressionFilter。 doFilter(CompressionFilter.java:131)
at org.eclipse.jetty.servlet.ServletHandler $ CachedChain.doFilter(ServletHandler.java:1650)
at org.eclipse.jetty.servlet.ServletHandler.doHandle( ServletHandler.java:583)
在org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
在org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler。 java:577)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
at org.eclipse.jetty.server.handler.ContextHan dler.doHandle(ContextHandler.java:1125)
在org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
在org.eclipse.jetty.server.session.SessionHandler。 doScope(SessionHandler.java:185)
在org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1059)
在org.eclipse.jetty.server.handler.ScopedHandler。在org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:215)
处使用org.eclipse.jetty.server.handler.HandlerCollection处理(ScopedHandler.java:141)
。处理(HandlerCollection.java:110)
在org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
在org.eclipse.jetty.server.Server.handle( Server.java:497)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:311)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:
at org.eclipse.jetty.io.AbstractConnection $ 2.run(Abst ractConnection.java:540)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:610)
at org.eclipse.jetty.util.thread.QueuedThreadPool $ 3.run (QueuedThreadPool.java:539)
和这一个
- 获取尝试失败!!!清理未完成的采集。在尝试获取所需的新资源时,我们未能成功超过允许的最大收购尝试次数(30)。
java.lang.NullPointerException $ b $ org.postgresql.Driver.parseURL(Driver.java:591)
at org.postgresql.Driver.acceptsURL(Driver.java: 429)
at java.sql.DriverManager.getDriver(DriverManager.java:299)
at com.mchange.v2.c3p0.DriverManagerDataSource.driver(DriverManagerDataSource.java:240)
at com .mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:131)
at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:156)
at com.mchange.v2 .c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:145)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool $ 1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:200)
at com.mchange.v2 .resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1086)
at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1073)
at com.mchange.v2.resourcepool.BasicResourcePool.access $ 800(BasicResourcePool.java:44)
在com.mchange.v2.resourcepool.BasicResourcePool $ ScatteredAcquireTask.run(BasicResourcePool.java:1810)
在com.mchange.v2.async.ThreadPoolAsynchronousRunner $ PoolThread.run(ThreadPoolAsynchronousRunner.java:648)
以下是我的MultiTenantIdentifier
public class MultitenantConnectionProvider实现MultiTenantConnectionProvider,ServiceRegistryAwareService {
private static final long serialVersionUID = 4368575201221677384L;
private C3P0ConnectionProvider connectionProvider = null;
@Override
public boolean supportsAggressiveRelease(){
return false;
$ b @Override
public void injectServices(ServiceRegistryImplementor serviceRegistry){
Map lSettings = serviceRegistry.getService(ConfigurationService.class).getSettings();
connectionProvider = new C3P0ConnectionProvider();
connectionProvider.injectServices(serviceRegistry);
connectionProvider.configure(lSettings);
$ b @Override
public boolean isUnwrappableAs(Class clazz){
return false;
}
@Override
public< T> T unwrap(Class< T> clazz){
return null;
$ b @Override
public Connection getAnyConnection()throws SQLException {
final Connection connection = connectionProvider.getConnection();
返回连接;
$ b @Override
public Connection getConnection(String tenantIdentifier)throws SQLException {
final Connection connection = getAnyConnection();
try {
connection.createStatement()。execute(SET SCHEMA'+ tenantIdentifier +');
}
catch(SQLException e){
抛出新的HibernateException(无法将JDBC连接更改为指定模式[+ tenantIdentifier +],e);
}
返回连接;
$ b @Override
public void releaseAnyConnection(Connection connection)throws SQLException {
try {
connection.createStatement()。execute(SET SCHEMA '上市');
}
catch(SQLException e){
抛出新的HibernateException(无法将JDBC连接更改为指定模式[public],e);
}
connectionProvider.closeConnection(connection);
$ b @Override
public void releaseConnection(String tenantIdentifier,Connection connection)throws SQLException {
releaseAnyConnection(connection);
和我的模式解析器
public class SchemaResolver implements CurrentTenantIdentifierResolver {
$ b @Override
public String resolveCurrentTenantIdentifier(){
返回tenant1; // TODO:实现服务以识别租户,如:userService.getCurrentlyAuthUser()。getTenantId();
}
@Override
public boolean validateExistingCurrentSessions(){
return false;
编辑:
附加信息:
我设置为粘贴的xml配置不会在运行时反映出来。在客户端数据源中,我指定了jdbc url,但是在运行时检查日志时,它没有被反映,因此'jdbc - > null'
我粘贴了错误的配置,事实证明我已经使用SchemaResolver和MultiTenantConnection Provider将hibernate配置为Mutlti-tenancy。 解决方案
对于那些和我有同样问题的人。这是我的发现和解决方案。
。)基于我的XML配置,我已经配置了DataSource(在这种情况下,C3P0ComboPooledDataSource)。 )在我的MultiTenantIdentifier上,我又一次配置了硬编码的依赖关系,即C3P0ConnectionProvider。配置将覆盖我在clientDataSource bean上指定的配置。
<属性名称=jpaProperties>配置C3P0ConnectionProvider at在此行。
<道具>
.....< / props>
< / property>
在这种情况下,没有jdbcUrl,Driver等。
结论:clientDataSource中的bean配置正在被硬编码的依赖关系覆盖。
解决方案。
不是在我的MultitenantConnectionProvider中创建新的DataSource。只需使用存在的唯一/由我的bean创建。像这样
public class MultitenantConnectionProvider实现MultiTenantConnectionProvider,ServiceRegistryAwareService {
private static final long serialVersionUID = 4368575201221677384L;
private org.slf4j.Logger logger = LoggerFactory.getLogger(MultitenantConnectionProvider.class);
private DataSource lazyDatasource = null;
@Override
public boolean supportsAggressiveRelease(){
return false;
$ b $ **
*我们使用的DataSource / ConnectionPool是由环境配置的
*在我们的例子中,默认情况下已配置(客户端数据源)
* /
@Override
public void injectServices(ServiceRegistryImplementor serviceRegistry){
Map lSettings = serviceRegistry.getService(ConfigurationService.class).getSettings();
lazyDatasource =(DataSource)lSettings.get(Environment.DATASOURCE);
}
@Override
public boolean isUnwrappableAs(Class clazz){
return false;
}
@Override
public< T> T unwrap(Class< T> clazz){
return null;
$ b / **
*从连接池中检索任何连接
* /
@Override
public Connection getAnyConnection()throws SQLException {
return lazyDatasource.getConnection();
$ b @Override
public Connection getConnection(String tenantIdentifier)throws SQLException {
final Connection connection = getAnyConnection();
try {
connection.createStatement()。execute(SET SCHEMA'+ tenantIdentifier +');
}
catch(SQLException e){
抛出新的HibernateException(无法将JDBC连接更改为指定模式[+ tenantIdentifier +],e);
}
返回连接;
$ b @Override
public void releaseAnyConnection(Connection connection)throws SQLException {
try {
connection.createStatement()。execute(SET SCHEMA '上市');
}
catch(SQLException e){
抛出新的HibernateException(无法将JDBC连接更改为指定模式[public],e);
}
connection.close();
$ b @Override
public void releaseConnection(String tenantIdentifier,Connection connection)throws SQLException {
releaseAnyConnection(connection);
}
}
接下来是配置文件。
< bean id =clientDataSourceclass =com.zaxxer.hikari.HikariDataSourcedestroy-method =close>
< property name =driverClassNamevalue =$ {driver.className}/>
< property name =jdbcUrlvalue =$ {db.url}/>
< property name =usernamevalue =$ {db.username}/>
< property name =passwordvalue =$ {db.password}/>
< property name =maximumPoolSizevalue =30/>
< property name =connectionTestQueryvalue =SELECT 1/>
< / bean>
< bean id =entityManagerFactoryclass =org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean>
< property name =dataSourceref =clientDataSource/>
< property name =packagesToScanvalue =org.brightworks.genesis.commons.model/>
< property name =jpaVendorAdapter>
< bean class =org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter>
< property name =databasePlatformvalue =$ {hibernate.sql.dialect}/>
< property name =showSqlvalue =true/>
< / bean>
< / property>
< property name =jpaProperties>
<道具>
< prop key =hibernate.format_sql> true< / prop>
< prop key =hibernate.multiTenancy> SCHEMA< / prop>
< prop key =hibernate.tenant_identifier_resolver> com.myprojec.SchemaResolver< / prop>
< prop key =hibernate.multi_tenant_connection_provider> com.myproj.hibernate.MultitenantConnectionProvider< / prop>
< /道具>
< / property>
< / bean>
结论:只需检索由Spring配置的当前/可用DataSource。 b
I am using Postgresql as my underlying Database and and letting Spring managed my DataSource/Connection pool. The configuration I have is this
<bean id="clientDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="org.postgresql.Driver"/>
<property name="jdbcUrl" value="jdbc:postgresql://localhost:5432/genesis_cms"/>
<property name="user" value="user"/>
<property name="password" value="password"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="clientDataSource"/>
<property name="packagesToScan" value = "org.myproject.package.commons.model.*"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">${hibernate.sql.dialect}</prop>
<prop key="hibernate.connection.pool_size">${hibernate.connection.pool_size}</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</prop>
<prop key="hibernate.connection.driver_class">org.postgresql.Driver</prop>
<prop key="show_sql">true</prop>
<prop key="hibernate.c3p0.min_size">5</prop>
<prop key="hibernate.c3p0.max_size">15</prop>
<prop key="hibernate.c3p0.timeout">300</prop>
<prop key="hibernate.c3p0.max_statements">50</prop>
<prop key="hibernate.c3p0.idle_test_period">3000</prop>
SCHEMA org.myproj.hibernate.SchemaResolver org.myproj.hibernate.MultitenantConnectionProvider
</props>
</property>
</bean>
<bean id = "transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
However, whenever I am booting up my application this log message appears.
Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@88f0b8ea [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@ce8fda44 [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, debugUnreturnedConnectionStackTraces -> false, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge0yw969iurgbvtwis0|6ee5f485, idleConnectionTestPeriod -> 3000, initialPoolSize -> 5, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 300, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 15, maxStatements -> 50, maxStatementsPerConnection -> 0, minPoolSize -> 5, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@ce2ef138 [ description -> null, driverClass -> null, factoryClassLocation -> null, identityToken -> 1hge0yw969iurgbvtwis0|ccd341d, jdbcUrl -> null, properties -> {} ], preferredTestQuery -> null, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false; userOverrides: {} ], dataSourceName -> null, factoryClassLocation -> null, identityToken -> 1hge0yw969iurgbvtwis0|53eba4b8, numHelperThreads -> 3 ]
I believe I have configured my settings correctly, Any idea how to debug this or solve this?
The Exception I am getting.
com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source.
at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1418)
at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:606)
at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:526)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutAndMarkConnectionInUse(C3P0PooledConnectionPool.java:755)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:682)
at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:140)
at org.hibernate.c3p0.internal.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:89)
at com.brightworks.genesis.client.config.hibernate.MultitenantConnectionProvider.getAnyConnection(MultitenantConnectionProvider.java:49)
at com.brightworks.genesis.client.config.hibernate.MultitenantConnectionProvider.getConnection(MultitenantConnectionProvider.java:55)
at org.hibernate.internal.AbstractSessionImpl$ContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:423)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:228)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:171)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.connection(StatementPreparerImpl.java:63)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:162)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:186)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:160)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1884)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1861)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838)
at org.hibernate.loader.Loader.doQuery(Loader.java:909)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
at org.hibernate.loader.Loader.doList(Loader.java:2553)
at org.hibernate.loader.Loader.doList(Loader.java:2539)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2369)
at org.hibernate.loader.Loader.list(Loader.java:2364)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:496)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:231)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1264)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:573)
at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:495)
at org.hibernate.jpa.criteria.compile.CriteriaQueryTypeQueryAdapter.getSingleResult(CriteriaQueryTypeQueryAdapter.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:360)
at com.sun.proxy.$Proxy52.getSingleResult(Unknown Source)
at org.springframework.data.jpa.repository.query.JpaQueryExecution$SingleEntityExecution.doExecute(JpaQueryExecution.java:197)
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:74)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:97)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:88)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:421)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:381)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$DefaultMethodInvokingMethodInterceptor.invoke(RepositoryFactorySupport.java:512)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:266)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:111)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy41.findByUsername(Unknown Source)
at org.brightworks.genesis.commons.service.account.impl.AccountServiceImpl.findByUsername(AccountServiceImpl.java:25)
at com.brightworks.genesis.client.webapp.controller.ProductController.addProductForm(ProductController.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:769)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1667)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.channel.ChannelProcessingFilter.doFilter(ChannelProcessingFilter.java:144)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1650)
at com.googlecode.webutilities.filters.CompressionFilter.doFilter(CompressionFilter.java:131)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1650)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:583)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1125)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1059)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:215)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:110)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:497)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:311)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:248)
at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:610)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:539)
And this one
- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception:
java.lang.NullPointerException
at org.postgresql.Driver.parseURL(Driver.java:591)
at org.postgresql.Driver.acceptsURL(Driver.java:429)
at java.sql.DriverManager.getDriver(DriverManager.java:299)
at com.mchange.v2.c3p0.DriverManagerDataSource.driver(DriverManagerDataSource.java:240)
at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:131)
at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:156)
at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:145)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:200)
at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1086)
at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1073)
at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:44)
at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1810)
at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:648)
And here's my MultiTenantIdentifier
public class MultitenantConnectionProvider implements MultiTenantConnectionProvider, ServiceRegistryAwareService {
private static final long serialVersionUID = 4368575201221677384L;
private C3P0ConnectionProvider connectionProvider = null;
@Override
public boolean supportsAggressiveRelease() {
return false;
}
@Override
public void injectServices(ServiceRegistryImplementor serviceRegistry) {
Map lSettings = serviceRegistry.getService(ConfigurationService.class).getSettings();
connectionProvider = new C3P0ConnectionProvider();
connectionProvider.injectServices(serviceRegistry);
connectionProvider.configure(lSettings);
}
@Override
public boolean isUnwrappableAs(Class clazz) {
return false;
}
@Override
public <T> T unwrap(Class<T> clazz) {
return null;
}
@Override
public Connection getAnyConnection() throws SQLException {
final Connection connection = connectionProvider.getConnection();
return connection;
}
@Override
public Connection getConnection(String tenantIdentifier) throws SQLException {
final Connection connection = getAnyConnection();
try {
connection.createStatement().execute("SET SCHEMA '" + tenantIdentifier + "'");
}
catch (SQLException e) {
throw new HibernateException("Could not alter JDBC connection to specified schema [" + tenantIdentifier + "]", e);
}
return connection;
}
@Override
public void releaseAnyConnection(Connection connection) throws SQLException {
try {
connection.createStatement().execute("SET SCHEMA 'public'");
}
catch (SQLException e) {
throw new HibernateException("Could not alter JDBC connection to specified schema [public]", e);
}
connectionProvider.closeConnection(connection);
}
@Override
public void releaseConnection(String tenantIdentifier, Connection connection) throws SQLException {
releaseAnyConnection(connection);
}
}
and My Schema Resolver
public class SchemaResolver implements CurrentTenantIdentifierResolver {
@Override
public String resolveCurrentTenantIdentifier() {
return "tenant1"; //TODO: Implement service to identify tenant like: userService.getCurrentlyAuthUser().getTenantId();
}
@Override
public boolean validateExistingCurrentSessions() {
return false;
}
}
EDIT:
ADDTIONAL INFO:
The configurations I've set to the xml I pasted is not being reflected upon runtime. inside the client data source, I've specified the jdbc url, however when checking the logs at run time, it wasn't being reflected hence the 'jdbc -> null'
I pasted the wrong configuration, it turns out that I have configured hibernate as Mutlti-tenancy with SchemaResolver and MultiTenantConnection Provider
解决方案
To those of you who were having the same problem as I did. Here's the findings and the solution I have.
1.) Based on my XML configuration, I have already configured the DataSource(In this case, The C3P0ComboPooledDataSource).
2.) On my MultiTenantIdentifier, I was again, configuring I have hard a coded Dependency, The C3P0ConnectionProvider. The configurations overrides the one I've specified on my clientDataSource bean. The configuration of the C3P0ConnectionProvider at is configured at this line.
<property name="jpaProperties">
<props>
.....</props>
</property>
Which in this case, does not have jdbcUrl,Driver, and etc.
Conclusion, My bean configuration at clientDataSource is being overriden by the hard coded dependency.
Solution.
Instead of creating a new DataSource in my MultitenantConnectionProvider. Just use the only that exists/being created by my bean. like this
public class MultitenantConnectionProvider implements MultiTenantConnectionProvider, ServiceRegistryAwareService {
private static final long serialVersionUID = 4368575201221677384L;
private org.slf4j.Logger logger = LoggerFactory.getLogger(MultitenantConnectionProvider.class);
private DataSource lazyDatasource = null;
@Override
public boolean supportsAggressiveRelease() {
return false;
}
/**
* The DataSource/ConnectionPool we are using is the one configured by the environment
* Which by default, in our case, is configured at client-persistence-cfg.xml
* (named Client Data Source)
*/
@Override
public void injectServices(ServiceRegistryImplementor serviceRegistry) {
Map lSettings = serviceRegistry.getService(ConfigurationService.class).getSettings();
lazyDatasource = (DataSource) lSettings.get(Environment.DATASOURCE);
}
@Override
public boolean isUnwrappableAs(Class clazz) {
return false;
}
@Override
public <T> T unwrap(Class<T> clazz) {
return null;
}
/**
* Retrieve any connection from the Connection Pool
*/
@Override
public Connection getAnyConnection() throws SQLException {
return lazyDatasource.getConnection();
}
@Override
public Connection getConnection(String tenantIdentifier) throws SQLException {
final Connection connection = getAnyConnection();
try {
connection.createStatement().execute("SET SCHEMA '" + tenantIdentifier + "'");
}
catch (SQLException e) {
throw new HibernateException("Could not alter JDBC connection to specified schema [" + tenantIdentifier + "]", e);
}
return connection;
}
@Override
public void releaseAnyConnection(Connection connection) throws SQLException {
try {
connection.createStatement().execute("SET SCHEMA 'public'");
}
catch (SQLException e) {
throw new HibernateException("Could not alter JDBC connection to specified schema [public]", e);
}
connection.close();
}
@Override
public void releaseConnection(String tenantIdentifier, Connection connection) throws SQLException {
releaseAnyConnection(connection);
}
}
Next, configuration files.
<bean id="clientDataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<property name="driverClassName" value="${driver.className}"/>
<property name="jdbcUrl" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
<property name="maximumPoolSize" value="30" />
<property name="connectionTestQuery" value="SELECT 1" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="clientDataSource"/>
<property name="packagesToScan" value = "org.brightworks.genesis.commons.model"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="${hibernate.sql.dialect}" />
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.multiTenancy">SCHEMA</prop>
<prop key="hibernate.tenant_identifier_resolver">com.myprojec.SchemaResolver</prop>
<prop key="hibernate.multi_tenant_connection_provider">com.myproj.hibernate.MultitenantConnectionProvider</prop>
</props>
</property>
</bean>
Conclusion: Just retrieve the current/available DataSource that's configured by Spring.
这篇关于C3P0受管连接池无法从其主要资源或工厂资源获取资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!