play 数据库访问
所属分类 play
浏览量 657
https://www.playframework.com/documentation/2.8.x/AccessingAnSQLDatabase
JDBC is a blocking operation
Play provides a plugin for managing JDBC connection pools
Play uses HikariCP as the default database connection pool implementation
play.db.pool=your.own.ConnectionPool
the default JDBC data source must be called default
the corresponding configuration properties are db.default.driver and db.default.url
db.default.driver
db.default.url
db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"
指定数据源名字
play.db.default = "primary"
db.primary.driver=org.h2.Driver
db.primary.url="jdbc:h2:mem:play"
db.default.jndiName=DefaultDS
db.default.logSql=true
@Singleton
class JavaApplicationDatabase {
private Database db;
private DatabaseExecutionContext executionContext;
@Inject
public JavaApplicationDatabase(Database db, DatabaseExecutionContext context) {
this.db = db;
this.executionContext = executionContext;
}
@Inject
public JavaNamedDatabase(
// inject "orders" database instead of "default"
@NamedDatabase("orders") Database db, DatabaseExecutionContext executionContext) {
this.db = db;
this.executionContext = executionContext;
}
public CompletionStage< Integer > updateSomething() {
return CompletableFuture.supplyAsync(
() ->
db.withConnection(
connection -> {
// do whatever you need with the db connection
return 1;
}),
executionContext);
}
using withConnection, the connection will be automatically closed at the end of the block
Connection connection = db.getConnection();
...
调用close 释放连接
添加依赖
libraryDependencies += jdbc
libraryDependencies += "com.h2database" % "h2" % "1.4.192"
完整例子代码
https://gitee.com/dyyx/hellocode/blob/master/demo/scala/play-rest-hello/app/controllers/DBController.scala
CustomExecutionContext
configure a custom execution context dedicated to serving JDBC operations
play.api.libs.concurrent.CustomExecutionContext
abstract class CustomExecutionContext(system: ActorSystem, name: String) extends ExecutionContextExecutor {
trait ExecutionContextExecutor extends ExecutionContext with Executor
scala.concurrent.ExecutionContextExecutor
scala.concurrent.ExecutionContext
java.util.concurrent.Executor
上一篇
下一篇
play HTTP routing
play框架日志
play框架依赖注入
依赖注入 guice 实例
scala 多行字符串
scala 元组和多重赋值