我以编程方式设置连接。
configuration.setProperty("hibernate.connection.url", "jdbc:mysql://" + host + ":" + port + "/" + dbName);
LOG.debug("{} Connection URL is jdbc:mysql://{}:{}/{}", Options.TAG, host, port, dbName);
configuration.setProperty("hibernate.connection.username", user);
configuration.setProperty("hibernate.connection.password", pass);
configuration.setProperty("hibernate.c3p0.preferredTestQuery", "SELECT 1");
configuration.setProperty("hibernate.c3p0.min_size", minConns);
configuration.setProperty("hibernate.c3p0.max_size", maxConns);
configuration.setProperty("hibernate.c3p0.max_statements", "50");
configuration.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
configuration.setProperty("hibernate.connection.pool_size", "1");
configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
configuration.setProperty("hibernate.current_session_context_class", "thread");
configuration.setProperty("hibernate.cache.provider_class", "org.hibernate.cache.internal.NoCacheProvider");
configuration.setProperty("hibernate.show_sql", "false");
configuration.addResource("TransactionBean.hbm.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
我收到警告
WARN BasicResourcePool:1851 - com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@6972975c
-- 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:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failure
从配置中可以看出,连接必须按照要求进行测试 configuration.setProperty(" hibernate.c3p0.preferredTestQuery"," SELECT 1"); 但是它没有经过测试。为什么不查询SELECT 1?
我的目标是在连接尚未建立的情况下获取例外。
答案 0 :(得分:1)
哦。如果连接尚未被获得,那么你永远不会看到连接测试失败。客户端将无法从池中检出连接。 (我猜想,当我第一次回答时,我错过了令你烦恼的警告。)在进行任何连接测试之前,池中必须有连接。使用testConnectionOnCheckout=true
,每个Connection客户端都会看到已经过测试。但这是Connection收购失败的完全不同的问题(上面的警告)
如果您的池无法获取任何连接,则客户端将暂停或超时(如果您已设置checkoutTimeout
)。如果池通常获取Connections,但偶尔因某些原因无法使已经获取的Connections无效,那么测试将正常运行,并且将在尝试获取新Connections时通过有时失败。如果失败的采集信号表明DBMS已关闭或不可用,当客户端尝试使用现在已断开的连接时,您将看到此警告和连接测试失败。
答案 1 :(得分:0)
您已设置preferredTestQuery
,如果将Connections设置为要测试,则会使用testConnectionOnCheckin
,但您实际上并未指定任何连接测试。为此,您需要设置testConnectionOnCheckout
,idleConnectionTestPeriod
和/或{{1}}。请参阅http://www.mchange.com/projects/c3p0/#configuring_connection_testing