Play Framework JDBC support library providing database access, connection pooling, and database configuration management for Play applications.
—
HikariCP-based connection pool implementation with comprehensive configuration options, performance monitoring, and lifecycle management.
Abstract interface for connection pool implementations.
trait ConnectionPool {
/** Create a data source with the given configuration */
def create(name: String, dbConfig: DatabaseConfig, configuration: Config): DataSource
/** Close the given data source */
def close(dataSource: DataSource): Unit
}Factory methods for creating connection pool instances.
object ConnectionPool {
/** Load a connection pool from a configured connection pool with Injector support */
def fromConfig(
config: String,
injector: Injector,
environment: Environment,
default: ConnectionPool
): ConnectionPool
/** Load a connection pool from configuration for compile-time DI */
def fromConfig(
config: String,
environment: Environment,
default: ConnectionPool
): ConnectionPool
/** Extract and process database URL, supporting shortcut formats */
def extractUrl(maybeUrl: Option[String], mode: Mode): (Option[String], Option[(String, String)])
/** Wrap a data source for SQL logging if logSql is enabled */
private[db] def wrapToLogSql(dataSource: DataSource, configuration: Config): DataSource
/** Unwrap a data source if it has been wrapped for SQL logging */
private[db] def unwrap(dataSource: DataSource): DataSource
}Usage Examples:
import play.api.db._
import play.api.Environment
// Create connection pool for compile-time DI
val environment = Environment.simple()
val defaultPool = new HikariCPConnectionPool(environment)
val pool = ConnectionPool.fromConfig("hikaricp", environment, defaultPool)
// URL extraction with credential parsing
val (extractedUrl, credentials) = ConnectionPool.extractUrl(
Some("postgres://user:pass@localhost:5432/mydb"),
play.api.Mode.Dev
)
// extractedUrl: Some("jdbc:postgresql://localhost:5432/mydb")
// credentials: Some(("user", "pass"))HikariCP-based implementation of the ConnectionPool interface.
@Singleton
class HikariCPConnectionPool @Inject()(environment: Environment) extends ConnectionPool {
/** Create a HikariCP data source with the given configuration */
override def create(name: String, dbConfig: DatabaseConfig, configuration: Config): DataSource
/** Close the HikariCP data source */
override def close(dataSource: DataSource): Unit
}Usage Examples:
import play.api.db._
import play.api.{Configuration, Environment}
import com.typesafe.config.ConfigFactory
val environment = Environment.simple()
val pool = new HikariCPConnectionPool(environment)
val dbConfig = DatabaseConfig(
driver = Some("org.postgresql.Driver"),
url = Some("jdbc:postgresql://localhost/myapp"),
username = Some("dbuser"),
password = Some("dbpass"),
jndiName = None
)
val config = ConfigFactory.parseString("""
hikaricp {
maximumPoolSize = 20
minimumIdle = 5
connectionTimeout = 30 seconds
idleTimeout = 10 minutes
maxLifetime = 30 minutes
}
""")
val dataSource = pool.create("myapp", dbConfig, config)
try {
val connection = dataSource.getConnection()
// Use connection...
connection.close()
} finally {
pool.close(dataSource)
}Comprehensive configuration options for HikariCP connection pools.
private[db] class HikariCPConfig(dbConfig: DatabaseConfig, configuration: Configuration) {
def toHikariConfig: HikariConfig
}Configuration Properties:
Essential configurations:
dataSourceClassName - Data source class name (alternative to driver/url)jdbcUrl - JDBC URL (from dbConfig.url)driverClassName - JDBC driver class (from dbConfig.driver)username - Database username (from dbConfig.username)password - Database password (from dbConfig.password)Frequently used:
autoCommit - Auto-commit behavior (default: true)connectionTimeout - Maximum wait time for connection (default: 30 seconds)idleTimeout - Maximum idle time before connection is retired (default: 10 minutes)maxLifetime - Maximum lifetime of a connection (default: 30 minutes)connectionTestQuery - Query to validate connectionsminimumIdle - Minimum number of idle connectionsmaximumPoolSize - Maximum number of connections in pool (default: 10)poolName - User-defined name for the connection poolInfrequently used:
initializationFailTimeout - Pool initialization failure timeoutisolateInternalQueries - Isolate internal pool queriesallowPoolSuspension - Allow pool suspensionreadOnly - Default read-only mode for connectionsregisterMbeans - Register JMX management beansconnectionInitSql - SQL executed after connection creationcatalog - Default catalog nametransactionIsolation - Default transaction isolation levelvalidationTimeout - Maximum time for connection validationleakDetectionThreshold - Connection leak detection thresholdConfiguration Example:
db.default {
driver = "org.postgresql.Driver"
url = "jdbc:postgresql://localhost/myapp"
username = "dbuser"
password = "dbpass"
# HikariCP specific settings
hikaricp {
# Pool sizing
minimumIdle = 5
maximumPoolSize = 20
# Connection timeouts
connectionTimeout = 30 seconds
idleTimeout = 10 minutes
maxLifetime = 30 minutes
# Connection testing
connectionTestQuery = "SELECT 1"
# Pool behavior
autoCommit = true
readOnly = false
# Monitoring
registerMbeans = true
leakDetectionThreshold = 60 seconds
# Data source properties
dataSource {
cachePrepStmts = true
prepStmtCacheSize = 250
prepStmtCacheSqlLimit = 2048
useServerPrepStmts = true
}
}
# SQL logging
logSql = false
}Support for shortcut URL formats with automatic credential extraction.
Supported URL Formats:
PostgreSQL shortcut:
postgres://username:password@host/databaseConverts to:
jdbc:postgresql://host/databaseMySQL shortcut:
mysql://username:password@host/databaseConverts to:
jdbc:mysql://host/database?useUnicode=yes&characterEncoding=UTF-8&connectionCollation=utf8_general_ciH2 development mode:
jdbc:h2:mem:testdbAutomatically adds DB_CLOSE_DELAY=-1 in development mode.
Usage Examples:
import play.api.db.ConnectionPool
import play.api.Mode
// PostgreSQL shortcut URL
val (pgUrl, pgCreds) = ConnectionPool.extractUrl(
Some("postgres://myuser:mypass@db.example.com/production"),
Mode.Prod
)
// pgUrl: Some("jdbc:postgresql://db.example.com/production")
// pgCreds: Some(("myuser", "mypass"))
// MySQL shortcut URL
val (mysqlUrl, mysqlCreds) = ConnectionPool.extractUrl(
Some("mysql://app:secret@mysql.example.com/appdb"),
Mode.Prod
)
// mysqlUrl: Some("jdbc:mysql://mysql.example.com/appdb?useUnicode=yes&characterEncoding=UTF-8&connectionCollation=utf8_general_ci")
// mysqlCreds: Some(("app", "secret"))
// H2 in development
val (h2Url, h2Creds) = ConnectionPool.extractUrl(
Some("jdbc:h2:mem:testdb"),
Mode.Dev
)
// h2Url: Some("jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1")
// h2Creds: NoneOptional SQL logging capability using jdbcdslog proxy.
private[db] def wrapToLogSql(dataSource: DataSource, configuration: Config): DataSource
private[db] def unwrap(dataSource: DataSource): DataSourceConfiguration:
db.default {
# Enable SQL logging
logSql = true
}When enabled, all SQL statements and their parameters are logged to the console, useful for development and debugging.
Support for binding data sources to JNDI names.
Configuration:
db.default {
driver = "org.postgresql.Driver"
url = "jdbc:postgresql://localhost/myapp"
jndiName = "java:comp/env/jdbc/MyAppDS"
}The data source will be automatically bound to the specified JNDI name during creation.
((core_count * 2) + disk_count) for typical OLTP workloadsdb.default {
hikaricp {
dataSource {
cachePrepStmts = true
prepStmtCacheSize = 250
prepStmtCacheSqlLimit = 2048
useServerPrepStmts = true
}
}
}db.default {
hikaricp {
leakDetectionThreshold = 60 seconds
registerMbeans = true
}
}connectionTimeoutregisterMbeans = true for pool metricsleakDetectionThreshold to detect leaked connectionslogSql = true for development debuggingInstall with Tessl CLI
npx tessl i tessl/maven-com-typesafe-play--play-jdbc-2-11