Golang 泛型实战 | 应用泛型构造体实现 gorm baseMapper
指标
实现一个根底数据库操作构造体,在 gorm 中一个新的表中可间接应用增删改查操作
实现
实例化数据库客户端
在这个例子中,咱们应用 MySQL
数据库进行示范,首先咱们须要实例化一个 MySQL 数据库客户端:
package mysql
import (
"brain/config" // 数据库参数保留在该配置文件中
"github.com/sirupsen/logrus"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"time"
)
var (Client *gorm.DB)
func init() {
if Client == nil {
var err error
Client, err = gorm.Open(mysql.Open(config.BrainCfg.Mysql.Source), &gorm.Config{})
db, _ := Client.DB()
db.SetMaxOpenConns(config.BrainCfg.Mysql.MaxOpenConn)
db.SetMaxIdleConns(config.BrainCfg.Mysql.MaxIdleConn)
db.SetConnMaxLifetime(time.Duration(config.BrainCfg.Mysql.ConnMaxLifeTime) * time.Second)
if err != nil {logrus.Errorf("mysql client create failed: %+v", err)
} else {logrus.Info("mysql client create successed")
}
}
}
定义泛型构造体
咱们定义一个泛型构造体BaseMapper
,在该构造体中实现数据库的增删改查操作:
package mapper
import (
"brain/internal/util/client/mysql"
"errors"
"github.com/sirupsen/logrus"
"gorm.io/gorm"
)
type BaseMapper[T any] struct {
}
func (m BaseMapper[T]) Insert(entity T) bool {logrus.Infof("insert %+v", entity)
err := mysql.Client.Create(&entity).Error
if err != nil {logrus.Errorf("insert %+v failed, %+v", entity, err)
return false
}
return true
}
func (m BaseMapper[T]) Delete(entity T) bool {logrus.Infof("delete %+v", entity)
err := mysql.Client.Delete(*&entity).Error
if err != nil {logrus.Errorf("delete %+v failed, %+v", entity, err)
return false
}
return true
}
func (m BaseMapper[T]) Update(entity T) bool {logrus.Infof("update %+v", entity)
err := mysql.Client.Updates(*&entity).Error
if err != nil {logrus.Errorf("update %+v failed, %+v", entity, err)
return false
}
return true
}
func (m BaseMapper[T]) List(entity T) (res []T) {logrus.Infof("list %+v", entity)
err := mysql.Client.Find(&res, *&entity).Error
if err != nil {logrus.Errorf("list %+v failed, %+v", entity, err)
}
return res
}
func (m BaseMapper[T]) Detail(entity T) (res T, err error) {logrus.Infof("detail %+v", entity)
result := mysql.Client.First(&res, *&entity)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {return res, result.Error}
return res, nil
}
泛型构造体的应用
假如咱们新增一个用户表,蕴含如下对象:
package entity
import "time"
type User struct {
ID string `gorm:"size:36;primaryKey" json:"id"`
NickName string `gorm:"size:128;not null" json:"nickName"`
Avatar string `gorm:"size:2048; not null" json:"avatar"`
CreateAt time.Time `gorm:"not null;autoCreateTime;type:timestamp" json:"createAt"`
UpdateAt time.Time `gorm:"not null;autoUpdateTime;type:timestamp" json:"updateAt"`
}
咱们要为用户表实现增删改查操作,仅须要如下操作即可:
package mapper
import (
"brain/internal/common/mapper"
"brain/internal/domain/user/entity"
"brain/internal/util/client/mysql"
"github.com/sirupsen/logrus"
)
type UserMapper struct {mapper.BaseMapper[entity.User]
}
func init() {err := mysql.Client.AutoMigrate(&entity.User{})
if err != nil {logrus.Errorf("MySQL 用户表迁徙失败: %+v", err)
}
}
而后在别的中央就能够间接应用
users := mapper.UserMapper{}.List(user)
调用对应的数据库办法啦
本文由博客一文多发平台 OpenWrite 公布!