- 创建model
package mysqltestimport ("errors""fmt""gorm.io/gorm"
)type Product struct {gorm.ModelID uint `gorm:"primarykey"`Name string `gorm:"column:name"`Price float64 `gorm:"column:price_value"`Test string `gorm:"-"`
}type Tabler interface {TableName() string
}// 修改表名
func (recv Product) TableName() string {return "product"
}// 钩子
func (recv *Product) BeforeCreate(tx *gorm.DB) (err error) {if recv.Name == "haha" {fmt.Println("不合法哈")return errors.New("不合法哈")} else {return nil}
}
- dbhelper
package mysqltestimport ("fmt""gorm.io/driver/mysql""gorm.io/gorm""gorm.io/gorm/clause"
)var db *gorm.DBfunc Initdb() {dsn := "ellis:ellis@tcp(192.168.214.134:3306)/go_db?charset=utf8mb4&parseTime=True&loc=Local"var err errordb, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})if err != nil {panic(err)}
}func Create(value interface{}) {d := db.Create(value)fmt.Printf("d.RowsAffected: %v\n", d.RowsAffected)
}func InitTable(table interface{}) {db.AutoMigrate(table)
}// 根据选择的字段插入
func CreateBySelectFields(fields []string, value interface{}) {db.Select(fields).Create(value)
}// 批量插入
func CreateMulti(value interface{}) {d := db.Create(value)fmt.Printf("d.RowsAffected: %v\n", d.RowsAffected)
}// 批量插入
func CreateBatch(value interface{}) {d := db.CreateInBatches(value, 100)fmt.Printf("d.RowsAffected: %v\n", d.RowsAffected)
}// 忽略钩子
func CreateIgnoreHook(value interface{}) {db.Session(&gorm.Session{SkipHooks: true}).Create(value)
}// 通过map创建
func CreateByMap(value map[string]interface{}, model interface{}) {db.Model(model).Create(value)
}// 冲突啥也不做
func DoNothingWhenInsert(value interface{}) {db.Clauses(clause.OnConflict{DoNothing: true}).Create(value)
}
- main
package mainimport ("ellis/mysqltest""fmt"
)func main() {mysqltest.Initdb()// 创建数据库mysqltest.InitTable(&mysqltest.Product{})// 添加单个数据mysqltest.Create(&mysqltest.Product{Name: "dafault"})// 添加数据忽略钩子mysqltest.CreateIgnoreHook(&mysqltest.Product{Name: "haha", Price: 100})// 选择字段进行插入var value *mysqltest.Product = &mysqltest.Product{Name: "twofield", Price: 100}mysqltest.CreateBySelectFields([]string{"Name", "Price"}, value)fmt.Printf("value: %v\n", value)// 批量插入var value1 []mysqltest.Product = []mysqltest.Product{mysqltest.Product{Name: "h1", Price: 1}, mysqltest.Product{Name: "h2", Price: 2}}mysqltest.CreateMulti(value1)fmt.Printf("value: %v\n", value1)// 批量插入var value3 []mysqltest.Product = []mysqltest.Product{mysqltest.Product{Name: "h1", Price: 1}, mysqltest.Product{Name: "h2", Price: 2}}mysqltest.CreateBatch(value3)fmt.Printf("value: %v\n", value3)// 通过map创建mysqltest.CreateByMap(map[string]interface{}{"Name": "ellis", "Price": "30000"}, mysqltest.Product{})// 冲突donothingmysqltest.DoNothingWhenInsert(&mysqltest.Product{ID: 1, Name: "ellis"})}
参考