go中的存储库模式和连接表

use*_*151 4 design-patterns domain-driven-design ddd-repositories go

我目前正在尝试围绕领域驱动设计、实体、服务、存储库构建我的应用程序...

所有基本的增删改查操作都很简单,基本上 1 个实体 => 1 个表 => 1 个存储库 => 1 个服务

但我无法找出处理两个实体之间的联接表的最干净的方法。

可以在联接内部按表进行 1 次查询,并且它会是“干净的”(可以这么说),但效率不高,因为简单的联接会导致一次查询。

在这种模式下,表格在哪里连接?

  • 我一直在考虑现在构建能够封装答案的实体,但这将有效地为 1 个查询创建 1 个实体 + 存储库...

  • 我还认为将多个实体合并到一个接口中可能会部分解决这个问题,但这会导致我的实体出现许多空参数(当您执行联接时,很少需要所有选项卡中的所有字段)

解决这个问题的正确方法/模式是什么,适合 DDD 或至少是干净的?

-- 编辑示例:

type User struct {
    ID          int       `db:"id"`
    ProjectID      int    `db:"project_id"`
    RoleID      int       `db:"role_id"`
    Email       string    `db:"email"`
    FirstName   string    `db:"first_name"`
    LastName    string    `db:"last_name"`
    Password    string    `db:"password"`
}

type UserRepository interface {
    FindById(int) (*User, error)
    FindByEmail(string) (*User, error)
    Create(user *User) error
    Update(user *User) error
    Delete(int) errorr
}

type Project struct {
    ID          int       `db:"id"``
    Name   string    `db:"name"`
    Description    string    `db:"description"`
}
Run Code Online (Sandbox Code Playgroud)

这里我有一个简单的用户存储库。我对“项目”表有类似的东西。可以创建表、获取项目的所有信息、删除等。

正如您所看到的,UserID 具有其所属项目 ID 的外键。

我的问题是当我需要从用户检索所有信息并说出“项目名称”和描述时。(我实际上表/实体有更多参数)

我需要对 user.project_id 和 project.id 进行简单的连接,并在一个查询中检索用户+项目名称+描述的所有信息。

有时会更复杂,因为会有 3-4 个实体像这样链接。(用户、项目、项目附加信息、角色等)

当然,我可以进行 N 次查询,每个实体一次。

user := userRepo.Find(user_id)
project := projectRepo.FindByuser(user.deal_id)
Run Code Online (Sandbox Code Playgroud)

这将“有效”,但我正在尝试找到一种方法来在一个查询中做到这一点。因为 user.project_id 和 project.id 上的简单 sql 连接将为我提供查询中的所有数据。

Ole*_*leg 5

至于 join 部分,你的问题很容易回答,但是对于 DDD 来说,当前的语言可能性存在很多障碍。但我会尝试一下..

好吧,让我们想象一下,我们正在开发一个支持多语言的教育课程后端,我们需要连接两个表并随后映射到对象。我们有两个表(第一个包含与语言无关的数据,第二个包含与语言相关的数据)如果您是存储库倡导者,那么您将拥有类似的内容:

// Course represents e.g. calculus, combinatorics, etc.
type Course struct {
    ID     uint   `json:"id" db:"id"`
    Name   string `json:"name" db:"name"`
    Poster string `json:"poster" db:"poster"`
}

type CourseRepository interface {
    List(ctx context.Context, localeID uint) ([]Course, error)
}
Run Code Online (Sandbox Code Playgroud)

然后为 sql db 实现它,我们将得到类似的东西:

type courseRepository struct {
    db *sqlx.DB
}

func NewCourseRepository(db *sqlx.DB) (CourseRepository, error) {
    if db == nil {
        return nil, errors.New("provided db handle to course repository is nil")
    }

    return &courseRepository{db:db}, nil
}

func (r *courseRepository) List(ctx context.Context, localeID uint) ([]Course, error) {

    const query = `SELECT c.id, c.poster, ct.name FROM courses AS c JOIN courses_t AS ct ON c.id = ct.id WHERE ct.locale = $1`
    var courses []Course
    if err := r.db.SelectContext(ctx, &courses, query, localeID); err != nil {
        return nil, fmt.Errorf("courses repostory/problem while trying to retrieve courses from database: %w", err)
    }

    return courses, nil
}
Run Code Online (Sandbox Code Playgroud)

这同样适用于不同的相关对象。您只需要耐心地对对象与基础数据的映射进行建模。让我再举一个例子。

type City struct {
    ID                      uint            `db:"id"`
    Country                 Country         `db:"country"`
}

type Country struct {
    ID   uint  `db:"id"`
    Name string `db:"name"`
}

// CityRepository provides access to city store.
type CityRepository interface {
    Get(ctx context.Context, cityID uint) (*City, error)
}

// Get retrieve city from database by specified id
func (r *cityRepository) Get(ctx context.Context, cityID uint) (*City, error) {

    const query = `SELECT 
    city.id, country.id AS 'country.id', country.name AS 'country.name',
    FROM city JOIN country ON city.country_id = country.id WHERE city.id = ?`

    city := City{}
    if err := r.db.GetContext(ctx, &city, query, cityID); err != nil {
        if err == sql.ErrNoRows {
          return nil, ErrNoCityEntity
        }
        return nil, fmt.Errorf("city repository / problem occurred while trying to retrieve city from database: %w", err)
    }

    return &city, nil
}
Run Code Online (Sandbox Code Playgroud)

现在,一切看起来都很干净,直到您意识到 Go 实际上(就目前而言)不支持泛型,而且在大多数情况下人们不鼓励使用反射功能,因为它会使您的程序变慢。为了让您完全不安,您想象从这一刻起您需要事务功能......

如果您来自其他语言,您可以尝试使用类似的方法来实现它:

// UnitOfWork is the interface that any UnitOfWork has to follow
// the only methods it as are to return Repositories that work
// together to achieve a common purpose/work.
type UnitOfWork interface {
    Entities() EntityRepository
    OtherEntities() OtherEntityRepository
}

// StartUnitOfWork it's the way to initialize a typed UoW, it has a uowFn
// which is the callback where all the work should be done, it also has the
// repositories, which are all the Repositories that belong to this UoW
type StartUnitOfWork func(ctx context.Context, t Type, uowFn UnitOfWorkFn, repositories ...interface{}) error

// UnitOfWorkFn is the signature of the function
// that is the callback of the StartUnitOfWork
type UnitOfWorkFn func(ctx context.Context, uw UnitOfWork) error
Run Code Online (Sandbox Code Playgroud)

我故意错过了一个实现,因为它对于 sql 来说看起来很可怕,值得它自己的问题(这个想法是工作单元的存储库版本在引擎盖下用启动的 tx 装饰),在解决这个问题之后,您将或多或少地拥有

err = svc.startUnitOfWork(ctx, uow.Write, func(ctx context.Context, uw uow.UnitOfWork) error {

            // _ = uw.Entities().Store(entity)
            // _ = uw.OtherEntities().Store(otherEntity)

            return nil
        }, svc.entityRepository, svc.otherEntityRepository)
Run Code Online (Sandbox Code Playgroud)

所以在这里你到达了最后,在大多数情况下,人们开始说你编写的代码似乎不符合习惯,指的是类似的东西。关键是概念写得太抽象,具体化的 DDD 是否适用于 Golang,或者你可以部分模仿它,这是一个哲学问题。如果您想要灵活性,请选择数据库一次并使用纯数据库句柄进行操作