简体   繁体   English

注入数据库连接池

[英]Inject database connection pool

I have started using MacWire for the dependency injection of my Play app, and I am having problems trying to inject the database connection. 我已经开始使用MacWire依赖注入我的Play应用程序,我在尝试注入数据库连接时遇到问题。

Before using DI, my code looked like this: 在使用DI之前,我的代码看起来像这样:

DB.withConnection { implicit connection =>
  ...
}

This is not working anymore after using DI. 使用DI后,这不再起作用了。 I get the following exception: java.lang.InstantiationException: play.api.db.DBApi . 我得到以下异常: java.lang.InstantiationException: play.api.db.DBApi

My application loader: 我的应用加载器:

class Loader extends ApplicationLoader {
  def load(context: Context) = {
    val components = new BuiltInComponentsFromContext(context) with Components
    components.application
  }
}

The main components of the app: 该应用程序的主要组件:

trait Components extends BuiltInComponents with I18nComponents
                 with RepositoryModule {

  lazy val assets: Assets = wire[Assets]
  lazy val router: Router = wire[Routes] withPrefix "/"
}

And the repository module: 和存储库模块:

trait RepositoryModule {
  lazy val userRepository = wire[UserRepository]
}

How can I get and use a database connection pool and inject it so it can be used within the repository? 如何获取和使用数据库连接池并将其注入,以便可以在存储库中使用?

I solved it using the DBComponents and BoneCPComponents traits in the RepositoryModule . 我使用RepositoryModuleDBComponentsBoneCPComponents特征解决了它。 With them, I could get a Database object and inject it to the repositories. 有了它们,我可以获得一个Database对象并将其注入存储库。 This is the code I'm using for the module: 这是我用于模块的代码:

trait RepositoryModule extends BuiltInComponents with DBComponents with BoneCPComponents {
  lazy val database: Database = dbApi.database("default")
  lazy val userRepository = wire[UserRepository]
}

The database "default" will use the db.default configurations in the application.conf . 数据库“默认”将使用db.default在配置application.conf The main problem with this solution is that you need to get the connections from the pool and return them when you're done. 此解决方案的主要问题是您需要从池中获取连接并在完成后返回它们。 I don't know if it can be improved to mimic the withConnection method. 我不知道是否可以改进模仿withConnection方法。

An example of the user repository using the injected database: 使用注入数据库的用户存储库示例:

class UserRepository(db: Database) {
  def deleteAdults: Unit = {
    val connection: Connection = db.getConnection()
    val removed: Int = SQL("DELETE * FROM User WHERE age > 18").executeUpdate()(connection)
    connection.close()
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM