public static DataSource createDataSource ( String url , String username , String password ) { String characterEncoding = Charset . defaultCharset ( ) . toString ( ) ; LOG . debug ( "Default character encoding: {}" , characterEncoding ) ; if ( ! Charset . defaultCharset ( ) . equals ( StandardCharsets . UTF_8 ) ) { // Character encoding must be set to UTF-8 in order for the database connection to work without error. // To override default encoding at runtime, run application jar with encoding environment variable set to // UTF-8 (or update IDE settings). TODO we should also check that JDBC and the database know to use UTF-8. throw new RuntimeException ( "Your system's default encoding (" + characterEncoding + ") is not supported. Please set it to UTF-8. Example: java -Dfile.encoding=UTF-8 application.jar" ) ; } // ConnectionFactory can handle null username and password (for local host-based authentication) ConnectionFactory connectionFactory = new DriverManagerConnectionFactory ( url , username , password ) ; PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory ( connectionFactory , null ) ; GenericObjectPool connectionPool = new GenericObjectPool ( poolableConnectionFactory ) ; // TODO: set other options on connectionPool? connectionPool . setMaxTotal ( 300 ) ; connectionPool . setMaxIdle ( 4 ) ; connectionPool . setMinIdle ( 2 ) ; poolableConnectionFactory . setPool ( connectionPool ) ; // We also want auto-commit switched off for bulk inserts, and also because fetches are super-slow with // auto-commit turned on. Apparently it interferes with result cursors. poolableConnectionFactory . setDefaultAutoCommit ( false ) ; return new PoolingDataSource ( connectionPool ) ; // We might want already-loaded feeds to be treated as read-only. // But we need to call this on the connection, not the connectionSource. // connection.setReadOnly(); // Not sure we need to close cursors - closing the pool-wrapped connection when we're done with it should also close cursors. // will this help? https://stackoverflow.com/a/18300252 // connection.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); }
Create an automatically managed pool of database connections to the supplied JDBC database URL .