播放:获取与默认数据库的连接 [英] Play: obtaining a connection to the default database

查看:75
本文介绍了播放:获取与默认数据库的连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得与我在 application.conf 中编写的数据库实例的连接:

I would like to obtain a connection to the Database instance that I define when I write this in application.conf:

db.default {
  driver = "com.mysql.jdbc.Driver"
  url = "jdbc:mysql://localhost/test"
  username = ...
  password = ...
}

文档说,我们应该将db: Database注入到控制器中(效果很好),并且没有其他显示方式.对此的预定义的Guice注入是隐藏的(不在 Module.scala 中).此外,它还建议由Play自动创建一个默认的数据库单例.

The docs say that we should inject db: Database into a controller (which works fine), and shows no other way. The predefined Guice injection for that is hidden (not in Module.scala). Also it suggests that a default Database singleton is created automatically by Play.

如果我不想将数据库注入控制器中,而是将关注点分开并仅在某些SqlHandler对象中使用它,该工作仅是执行SQL查询,那该怎么办:

What if I don't want to inject the database into a controller, but separate concerns and use it only in some SqlHandler object which only job is to do SQL queries:

object SqlHandler {
  val db: Database = ???
  def select(params) {...db...}
  def insert(params) {...db...}
}

我知道我可以使用

I know that I can create a new Database instance with play.api.db.Databases with something like

import play.api.db.Databases
val db: Database = Databases(
  driver = "com.mysql.jdbc.Driver"
  url = "jdbc:mysql://localhost/test"
  username = ...
  password = ...
)

不仅我发现重复所有信息都是愚蠢的,而且我相信它还会创建两次数据库(一次自动创建,一次手动创建,不是吗?).

but not only do I find stupid to repeat all the information, I believe it also creates the Database twice (once automatically, once here manually, doesn't it?).

是否有任何便捷的方法来获取到默认数据库的连接,或者如何我可以使用Guice将其注入到其他地方?

Is there any convenience method to obtain a connection to my default Database, or how can I use Guice to inject it somewhere else?

推荐答案

此答案假定您要将SqlHandler注入到控制器中.

This answer assumes you want to inject your SqlHandler into a controller.

如果是这样,您可以在控制器中执行此操作:-

If so, you can just do this in your controller:-

class Application @Inject() (sql: SqlHandler) extends Controller {

  def index = Action { implicit request =>
    ...    
    sql.someSQLHandlerBehaviour()
    ...
  }
}

由于控制器是由Guice开箱即用地管理的,因此任何注射剂也将落在Guice生命周期管理的范围内.因此,您应该只能将SqlHandler注入到如上所述的控制器中.

Since controllers are managed by Guice out-of-the-box, any injectables will also fall within the scope of Guice's life-cycle management. So you should just be able to inject your SqlHandler into a controller as above.

并且由于您的SqlHandler现在由Guice管理,因此您可以像这样将jdbc依赖项注入到SqlHandler中.

And since your SqlHandler is now under the management of Guice, you can inject the jdbc dependencies into SqlHandler like so.

@Singleton
class SqlInjector @Inject() (db: Database) { ... }

这篇关于播放:获取与默认数据库的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆