Slick:更新在之后获取时不可用

Slick: Updates not available when fetched just after

我正在尝试 this slick example and when I try to create an entry and then fetch that right after, I don't get the record. I modified the test case which is here 如下。

val response = create(BankProduct("car loan", 1)).flatMap(getById)
whenReady(response) { p =>
  assert(p.get === BankProduct("car loan", 1))
}

以上失败,因为无法立即获取创建的 BankProduct。 它为此使用 h2 db,下面是配置。

trait H2DBComponent extends DBComponent {

  val logger = LoggerFactory.getLogger(this.getClass)

  val driver = slick.driver.H2Driver

  import driver.api._

  val randomDB = "jdbc:h2:mem:test" + UUID.randomUUID().toString() + ";"

  val h2Url = randomDB + "MODE=MySql;DATABASE_TO_UPPER=false;INIT=runscript from 'src/test/resources/schema.sql'\;runscript from 'src/test/resources/schemadata.sql'"

  val db: Database = {
    logger.info("Creating test connection")
    Database.forURL(url = h2Url, driver = "org.h2.Driver")
  }
}


private[repo] trait BankProductTable extends BankTable { this: DBComponent =>

  import driver.api._

  private[BankProductTable] class BankProductTable(tag: Tag) extends Table[BankProduct](tag, "bankproduct") {
    val id = column[Int]("id", O.PrimaryKey, O.AutoInc)
    val name = column[String]("name")
    val bankId = column[Int]("bank_id")
    def bank = foreignKey("bank_product_fk", bankId, bankTableQuery)(_.id)
    def * = (name, bankId, id.?) <> (BankProduct.tupled, BankProduct.unapply)

  }

  protected val bankProductTableQuery = TableQuery[BankProductTable]

  protected def bankProductTableAutoInc = bankProductTableQuery returning bankProductTableQuery.map(_.id)

}

我不明白为什么会发生这种情况以及如何避免这种情况? 我也尝试添加 属性 autoCommit 但它也不起作用。

感谢任何有助于澄清这种歧义的帮助。

这可能是由于 create 调用关闭连接后内存中的数据库内容丢失。根据docs:

By default, closing the last connection to a database closes the database. For an in-memory database, this means the content is lost. To keep the database open, add ;DB_CLOSE_DELAY=-1 to the database URL. To keep the content of an in-memory database as long as the virtual machine is alive, use jdbc:h2:mem:test;DB_CLOSE_DELAY=-1.

但是添加DB_CLOSE_DELAY=-1后,由于

会出现错误
runscript from 'src/test/resources/schemadata.sql' 

executed on each connection,因此需要进行重构,以便在初始化时仅填充一次数据库。