如何在Play之外使用Anorm?

时间:2014-08-30 13:12:27

标签: scala playframework anorm

你如何在Scala游戏之外使用Anorm?在Anorm文档中,它只是使用类似的东西:

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

DB对象仅适用于Play。如何在不使用Play的情况下单独使用Anorm?

3 个答案:

答案 0 :(得分:14)

不需要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?

答案 1 :(得分:1)

你也可以按如下方式模拟数据库对象(虽然我没试过)

 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

答案 2 :(得分:0)

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

要包含在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)
  }
相关问题