【问题标题】:Repository pattern with transactional query具有事务查询的存储库模式
【发布时间】:2021-07-06 10:29:09
【问题描述】:

我正在编写一个可以进行事务查询的服务,(在这个问题中我将使用 GORM)

用户服务

type userService struct {
    UserRepository  repository.IUserRepository
    TokenRepository repository.ITokenRepository
}

type IUserService interface {
WithTrx() IUserService
CommitTrx() error
RollbackTrx()

Create(ctx context.Context, name string) (*model.User, error)
...
...
}

这里是服务的一些实现

user.go

func (s *userService) WithTrx() IUserService {
    newService := &userService{
        UserRepository:       s.UserRepository.WithTrx(),
        TokenRepository:      s.TokenRepository,
    
    }
    return newService
}
func (s *userService) Create(ctx context.Context, name string) (*model.User, error) {
... 
// s.UserRepository.Create() 
// then return the user, error 
...
}


对于 UserRepository.WithTrx() 基本上只是返回接口本身

type psqlUserRepository struct {
    DB *gorm.DB
}

type IUserRepository interface {
    WithTrx() IUserRepository
    CommitTrx() error
    RollbackTrx()

    Create(ctx context.Context, u model.User) (*model.User, error)
...
}

func (r *psqlUserRepository) WithTrx() IUserRepository {
    return &psqlUserRepository{DB: r.DB.Begin()}
}

所以当我需要用户服务来使用事务查询创建用户时,我只是:


trx:= userserviceInstance.WithTrx()
user, err := trx.Create(ctx, name)
// err handling and rollback
commitErr := trx.CommitTrx()

有没有类似的方法?这叫什么?我不确定这是否是创建事务查询的正确模式。

【问题讨论】:

    标签: go repository-pattern transactional-database


    【解决方案1】:

    我想这里有一些时间。

    存储库模式通常用于隐藏存储的实现细节。

    事务是一个技术细节,不应暴露给更高层。

    换句话说,您拥有的存储库接口(架构元素)不应该公开事务(技术细节)。

    有没有类似的方法?这叫什么?我不是 确定这是否是创建事务查询的正确模式 您可能想了解更多关于对您的目的有用的工作单元模式。

    你可以看看工作单元模式。

    以下是一些您可能会觉得有用的示例:

    【讨论】:

      猜你喜欢
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-02
      • 2012-07-13
      • 2013-02-04
      相关资源
      最近更新 更多