Reputation: 111
HikariCP version: 2.6.1
JDK version : 1.8.0_111
Database : MySQL
Driver version : 5.1.6
This is my code:
HikariConfig config = new HikariConfig();
config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
config.setJdbcUrl("jdbc:mysql://localhost:3306/mydatabase");
config.setUsername("root");
config.setPassword("root");
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
System.out.println("Hikari datasource: " + config.getDataSource());
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase?"
+ "user=root&password=root");
System.out.println("Conn: " + conn);
String select = "SELECT * FROM users WHERE email = ? AND enable = 'Y'";
PreparedStatement ps = conn.prepareStatement(select);
ps.setString(1, "[email protected]");
ResultSet rs = ps.executeQuery();
System.out.println(rs.next());
The line System.out.println( "Hikari datasource: " + config.getDataSource() );
returns null and the line System.out.println( rs.next() );
returns true.
In other words, Hikari connection is not working for some reason. I also can connect using Wildfly Datasource.
Any idea?
Upvotes: 2
Views: 2993
Reputation: 108981
The method HikariConfig.getDataSource()
does not do what you think it does. It doesn't provide you with a Hikari DataSource
, it returns the (non-pooling) data source you have set yourself (if any); which you haven't done in your code, so it returns null
.
As specified in the documentation:
dataSource
This property is only available via programmatic configuration or IoC container. This property allows you to directly set the instance of theDataSource
to be wrapped by the pool, rather than having HikariCP construct it via reflection. This can be useful in some dependency injection frameworks. When this property is specified, thedataSourceClassName
property and all DataSource-specific properties will be ignored. Default: none
To create the Hikari data source, you need to use:
HikariDataSource ds = new HikariDataSource(config);
Then you should not use DriverManager
to get the connection, but the data source instead:
ds.getConnection()
See also the initialization example on the HikariCP page.
Also: make sure you close your connections properly (which returns the connection to the pool), your current code doesn't do that. The easiest thing (in Java 7 or higher), is to use try-with-resources:
try (Connection conn = ds.getConnection()) {
// use conn...
}
// conn will have been automatically closed (returned to the pool)
Upvotes: 4