我有autoInc主key('id')
的表格,但我需要通过另一列控制表格中记录的唯一性(列'代码')。
我试着这样做:
def findByCode(code: String): Future[Option[A]] =
try db.run(tableQuery.filter(_.code === code).result.headOption)
def insert(entity: A): Future[Int] =
try db.run(tableQuery += entity)
def insertIfNotExists(code: String, entity: A): Future[Int] = {
findByCode(code).flatMap {
case None => insert(entity)
case _ => Future(-1)
}
}
方法findByCode
和insert分别返回Future[A]
和Future[Int]
。
当我在要插入的一些记录上运行此代码时,我意识到findByCode
没有找到已经插入的记录,并且我得到了大量的记录重复。作为一种解决方法,我在我的数据库中构建了一个约束(由postgres驱动),但是我想知道我是否在代码中做了错误,或者它可能无法保证检查记录是否存在当我刚才插入另一个并发事务?
对于我的目的,什么是最佳推荐方式?
1)构建唯一性约束并包装插入int try块? (我现在用它)
2)使用带有一个查询的plainsql实现insertOrUpdate(插入到不存在的地方(选择where ...))
3)为这样的查询编写一个同步包装器(使用Await)并在一个线程中同步运行它们
4)smth else
提前感谢任何建议。