简体   繁体   English

清洁架构 - 如何解决数据库事务?

[英]Clean Architecture - how to address database transactions?

In 'clean architecture' the interactors (use cases) are responsible for defining busines logic. 在“干净架构”中,交互者(用例)负责定义业务逻辑。 Most of the examples define use cases in such a way: 大多数示例以这种方式定义用例:

public MyUseCase() {

  public boolean execute(...) {
    int id = repository.insert(a)
    if(id > 0) {
      b.aId= id;
      repository.insert(b);
      ...
    }
  }
}

Interactors use mostly simple CRUD like operations or queries on repository. Interactors主要使用简单的CRUD操作或存储库查询。 The above example is synchronous for the case of simplicity but you can find repos with the same approach using asynchronous solutions like callbacks or rxjava. 上面的示例在简单的情况下是同步的,但您可以使用异步解决方案(如回调或rxjava)以相同的方法找到repos。

But what about use case inegrity. 但是用例不完整呢? For instance, you can't be 100% sure that after inserting a it will still be there when you insert b . 举例来说,你不能100%肯定,在插入后a它仍然会在那里,当你插入b What if after inserting a you get some RepositoryException while inserting b . 如果在插入之后插入b会得到一些RepositoryException, a怎么办?

All the repos I've seen so far don't take it into account, so my question is: 我到目前为止看到的所有回购都没有考虑到,所以我的问题是:

What's the solution of the above problem in clean architecture? 清洁架构中上述问题的解决方案是什么?

This answer may be kinda late, but I have struggled with the same problem and came to a conclusion that transaction management is, in fact, part of a Use Case - like, "If something goes wrong with B, revert A's state". 这个答案可能有点晚了,但我一直在努力解决同样的问题,并得出结论,事务管理实际上是用例的一部分 - 比如,“如果B出现问题,还原A的状态”。 So, it can and should be explicitly stated within your UseCase, probably with some kind of "DataManagerRepo", like this: 因此,它可以而且应该在您的UseCase中明确说明,可能使用某种“DataManagerRepo”,如下所示:

public MyUseCase() {

    public boolean execute(...) {
        dataManagerRepository.openTransaction()
        try {
            int id = repository.insert(a)
            if(id > 0) {
            b.aId= id;
            repository.insert(b);
            ...
        }
        catch (MyException exc) {
            dataManagerRepository.rollbackTransaction()
        }

        dataManagerRepository.commitTransaction()
    }
}

Names may vary to abstract away integrity mechanism, but the idea is the same. 名称可能会有所不同,以抽象出完整性机制,但这个想法是一样的。 I hope this will help somebody. 我希望这会对某人有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM