【问题标题】:Slick access to DataSource Programmatically以编程方式灵活访问数据源
【发布时间】:2019-09-06 16:13:35
【问题描述】:

我有一个这样的对象:

object DatabaseFactory {

  import slick.jdbc.PostgresProfile.api._

  private val db = Database.forConfig("database.postgresql")

  def getDatabase = db
}  

还有这样的配置:

database {
    postgresql {
      connectionPool = "HikariCP"
      dataSourceClass = "org.postgresql.ds.PGSimpleDataSource"
      properties = {
          serverName = "localhost"
          portNumber = "5432"
          databaseName = "myProject"
          user = "user"
          password = "userPass"
      }
      numThreads = 10
    }
} 

有什么方法可以从 slick 获取 javax.sql.DataSource 吗?
我需要一个来自 slick 的 PGSimpleDataSource 实例。

我想在 Flyway 配置中使用它:

Flyway.configure()
      .baselineOnMigrate(true)
      .locations("filesystem:/etc/myProject/db-scripts")
      .dataSource(??? Need DataSource ???)

【问题讨论】:

标签: scala slick slick-3.0


【解决方案1】:

我刚刚偶然发现了这一点,并看到了 https://stackoverflow.com/users/337134/knows-not-much 的评论。 基本上,您需要实现自己的 Datasource 实例:

package slick.migration.api.flyway

import java.io.PrintWriter
import java.sql.{DriverManager, SQLException, SQLFeatureNotSupportedException}

import slick.jdbc.JdbcBackend

import javax.sql.DataSource


class DatabaseDatasource(database: JdbcBackend#Database) extends DataSource {
  override def getConnection = database.createSession().conn
  override def getConnection(username: String, password: String) = throw new SQLFeatureNotSupportedException()
  override def unwrap[T](iface: Class[T]) =
    if (iface.isInstance(this)) this.asInstanceOf[T]
    else throw new SQLException(getClass.getName + " is not a wrapper for " + iface)
  override def isWrapperFor(iface: Class[_]) = iface.isInstance(this)
  override def getLogWriter = throw new SQLFeatureNotSupportedException()
  override def setLogWriter(out: PrintWriter): Unit = throw new SQLFeatureNotSupportedException()
  override def setLoginTimeout(seconds: Int): Unit = DriverManager.setLoginTimeout(seconds)
  override def getLoginTimeout = DriverManager.getLoginTimeout
  override def getParentLogger = throw new SQLFeatureNotSupportedException()
}

【讨论】:

    【解决方案2】:

    有什么方法可以从 slick 获取 javax.sql.DataSource 吗?

    我不这么认为,但我能够获得一个 slick.jdbc.JdbcDataSource 的实例,然后我使用了与我一直使用 javax.sql.DataSource 完全相同的方式。创建连接,然后是preparedstatement,然后处理结果集。都一样。

    db.source
    

    我知道这是旧的,但想提供一个选项来尝试,它不像创建自己的数据源实例的其他答案那样激烈。

    【讨论】:

      猜你喜欢
      • 2018-08-14
      • 1970-01-01
      • 2012-12-18
      • 2010-12-20
      • 1970-01-01
      • 1970-01-01
      • 2010-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多