【问题标题】:Slick Repo methods all participating in one Service's Transaction所有参与一项服务交易的 Slick Repo 方法
【发布时间】:2015-09-08 08:10:16
【问题描述】:

我目前有一组以约定*SlickRepo 命名的数据访问对象。比如UserSlickRepoDistributionSlickRepoContentSlickRepo等等……

每个 Repos 上都有基本遵循此约定的方法:

trait SomethingRepoImpl extends SomethingRepo {
  val somethingRepo: SomethingRepo = new SomethingRepoImpl

  class SomethingRepoImpl extends SomethingRepo with MySlickDatastore {

    def getSomething(id: UUID): Either[SomethingNotFoundError, Something] = {
      getDatabase withDynSession {
        // Slick stuff
      }
    }
    def createSomething .....
  }
}

现在在服务级别,我们在这个 repo 类中烘焙,我们有如下所示的方法:

trait SomethingServiceImpl extends SomethingService {

  dep: SomethingRepo with SomethingElseRepo =>


  val somethingService = new SomethingServiceImpl

  class SomethingServiceImpl extends SomethingService {

    def createSomethingGood(): Either[SomeError, (Something, SomethingElse)] = {
      (dep.somethingRepo.createSomething, dep.somethingElseRepo.createSomethingElse)
    }

  }
}

我们现在希望createSomethingGood 在一个事务中实际运行两个 repo 方法。由于所有 Slick 的东西都被锁定在 Slick 特定的 Repo 方法中,那么最好的方法是什么?我不反对在我的*ServiceImpl 类中使用特定于 Slick 的代码(我的意思是很奇怪,但没关系),但这是否意味着我必须更改我的 Repo 类以一起删除 getDatabase withDynSession 类型代码,而是通过在服务层的会话中?对我来说,这似乎......错了。

【问题讨论】:

  • 您可以拥有一个带有隐式会话的事务服务suggested here。旁注:你确定你的 Repos 实际上是 Repositories,而不是 DAO 对象?

标签: scala slick-2.0


【解决方案1】:

在我看来,正确的方法是将createSomethingcreateSomethingElse 添加到一个*RepoSomethingRepoSomethingElseRepo)事务方法(withTransaction {...})。这不是一个漂亮的解决方案,但对我来说尽可能简单,因为这些实体在逻辑上是连接的(我们可以从这段代码中看到 (dep.somethingRepo.createSomething, dep.somethingElseRepo.createSomethingElse)),我认为在一个 DAO 类中混合对 2 个实体进行操作并不是什么大问题。如果我错了,请纠正我。

【讨论】:

  • 我不确定在我的情况下,只要服务方法需要在事务中调用两个 repo 调用时创建自定义 *Repo 类是否可行。
  • @ThaDon,不创建自定义但重用已经存在的一个。在您的示例中,它们是 SomethingRepoSomethingElseRepo
【解决方案2】:

也许还有其他方法。我自己没有尝试过,但想法是您可以拥有一个实际传递给 Repo 的 Session 包装器。

该包装器必须在服务层创建,但您可以在伴随对象上抽象特定实现,因此服务层实际上并不处理 Slick,而是类似

SessionWrapper.transactional: Session

我希望这会有所帮助,如果我得到更改自己尝试一下,我会在回复中添加更多内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    相关资源
    最近更新 更多