【问题标题】:How to use Anorm outside of Play?如何在 Play 之外使用 Anorm?
【发布时间】:2014-10-24 07:40:02
【问题描述】:

您如何在 Scala 中使用 Anorm?在用于播放的 Anorm 文档中,它只是使用如下内容:

DB.withConnection { implicit c =>
  val result: Boolean = SQL("Select 1").execute()    
} 

DB 对象仅用于 Play。如何不使用 Play 单独使用 Anorm?

【问题讨论】:

  • 您提供的c 是数据库连接对象,即java.sql.Connection。您可以提供真实的连接并将其作为隐式提供。

标签: scala playframework anorm


【解决方案1】:

不需要DB 对象(Play JDBC 不是 Anorm 的一部分)。 Anorm 与您提供隐式连接一样工作:

implicit val con: java.sql.Connection = ??? // whatever you want to resolve connection

SQL"SELECT * FROM Table".as(...)

您可以通过多种方式解析 JDBC 连接:基本的DriverManager.getConnection、JNDI、...

至于依赖,在SBT中很容易添加:How to declare dependency on Play's Anorm for a standalone application?

【讨论】:

【解决方案2】:

您也可以按如下方式模拟 DB 对象(虽然我还没有尝试过)

 object DB {
    def withConnection[A](block: Connection => A): A = {
      val connection: Connection = ConnectionPool.borrow()

      try {
        block(connection)
      } finally {
        connection.close()
      }
    }
  }

取自https://github.com/TimothyKlim/anorm-without-play/blob/master/src/main/scala/Main.scala

【讨论】:

    【解决方案3】:

    在下面记录对我有用的代码:

    要包含在build.sbt 中的依赖项:

    // https://mvnrepository.com/artifact/org.playframework.anorm/anorm
    libraryDependencies += "org.playframework.anorm" %% "anorm" % "2.6.7"
    

    编写辅助类:

        @Singleton
        class DBUtils {
        
          val schema = AppConfig.defaultSchema
        
          def withDefaultConnection(sqlQuery: SqlQuery) = {
    // could replace with DBCP, not got a chance yet
            val conn = DriverManager.getConnection(AppConfig.dbUrl,AppConfig.dbUser, AppConfig.dbPassword)
            val result = Try(sqlQuery.execute()(conn))
            conn.close()
            result
          }
        }
        object DBUtils extends DBUtils
    

    接下来,任何查询都可以使用withDefaultConnection方法执行:

      def saveReviews(listOfReviews: List[Review]):Try[Boolean]= {
        val query = SQL(
          s"""insert into aws.reviews
             | (                 reviewerId,
             |                 asin,
             |                 overall,
             |                 summary,
             |                 unixReviewTime,
             |                 reviewTime
             | )
             |values ${listOfReviews.mkString(",")}""".stripMargin)
        //println(query.toString())
        DBUtils.withDefaultConnection(query)
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-15
      • 1970-01-01
      • 2014-04-21
      • 1970-01-01
      相关资源
      最近更新 更多