Play error on startup: No implementation for play.api.db.Database was bound

时光总嘲笑我的痴心妄想 提交于 2019-12-05 06:28:14

In my case application.conf didn't have proper db parameters

example

  db.default.driver = org.h2.Driver
  db.default.url = "jdbc:h2:mem:play"
  db.default.username = sa
  db.default.password = ""

Your application.conf should look like below:

db.dev_mysql {
  driver = "org.mariadb.jdbc.Driver" 
  # JDBC connection string. "useAffectedRows" must be set to true.
  url = "jdbc:mysql://dev01:3306/dev_db?autoReconnect=true&characterEncoding=utf-8&connectionCollation=utf8_unicode_ci&useSSL=false&useAffectedRows=true"

  url = ${?DATABASE_URL}
  hikaricp {
    # Whether autocommit should be used
    autoCommit = true
    # The connection timeout
    connectionTimeout = 10 seconds
    # The idle timeout
    idleTimeout = 5 minutes
    # The max lifetime of a connection
    maxLifetime = 10 minutes
    # If non null, the query that should be used to test connections
    connectionTestQuery = "SELECT 1"
    # Minimum number of idle connections maintained in the pool.
    minimumIdle = 10
    # The maximum number of connections to make.
    maximumPoolSize = 20
    # If non null, sets the name of the connection pool. Primarily used for stats reporting.
    poolName = "mysql"
    # A SQL statement that will be executed after every new connection creation before adding it to the pool
    connectionInitSql = "SELECT 1"
    # If non null, sets the transaction isolation level
    transactionIsolation = TRANSACTION_READ_COMMITTED
    # The validation timeout to use
    validationTimeout = 5 seconds
  }
}

When Play starts, it creates a database connection-pool with the name of dev_mysql by loading the params from db.dev_mysql json in application.conf

How to execute queries :

We can use a NamedDatabase annotation.

class CustomController @Inject() (
                                             val config: Configuration,
                                             @play.db.NamedDatabase("dev_mysql") db : Database,
                                             controllerComponents: ControllerComponents,
                                           ) extends ApiController(controllerComponents)  {
    def createReportDefinition = Action { implicit ctx ⇒

      val conn = db.getConnection(false)
      val sqlQuery = "select 1"
      val prepStmt: PreparedStatement = conn.prepareStatement(sqlQuery)
      prepStmt.execute()
      conn.commit()
      conn.close()
      Ok
      }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!