Ã¥ÂÂè¨Â
Ã¥ÂÂ两ç¯Âç¬Âè®°åÂÂå«ä»Âç»Â亠Golang å¾®æÂÂå¡ HTTP æ¡Âæ¶ Hertz å Golang å¾®æÂÂå¡ RPC æ¡Âæ¶ Kitexï¼Âæ¾ÂÂå°Âè¦Âä»Âç»Âé¢åÂÂORM(æÂÂä¹ å±Â)æ¡Âæ¶ GORMãÂÂ
GORM æ¯é¢å Golang è¯Âè¨ÂçÂÂä¸Â秠ORM(æÂÂä¹ å±Â)æ¡Âæ¶ï¼Âæ¯æÂÂå¤Âç§Âæ°æ®åºÂçÂÂæ¥堥ï¼Âä¾Â妠MySQLï¼ÂPostgreSQLï¼ÂSQLiteï¼ÂSQL Serverï¼ÂClickhouseãÂÂæ¤æ¡Âæ¶çÂÂç¹ç¹ï¼Âå¼±åÂÂäºÂå¼ÂÃ¥ÂÂè 对亠SQL è¯Âè¨ÂçÂÂæÂÂæ¡ç¨Â度ï¼Â使ç¨æÂÂä¾Âç API è¿Âè¡ÂåºÂå±Âæ°æ®åºÂçÂÂ访é®ãÂÂ
GORM å®Âæ¹æ¯æÂÂçÂÂæ°æ®åºÂç±»åÂÂæÂÂï¼ MySQL, PostgreSQL, SQlite, SQL ServerãÂÂ
ä½Âè æ¯ä¸Âå½人ï¼Âä¸ÂæÂÂæÂÂæ¡£é½Âå ¨ï¼Â对å¼ÂÃ¥ÂÂè åÂÂ好ï¼Âæ¯æÂÂ主æµÂæ°æ®åºÂãÂÂ
ç¹ç¹ï¼Â
- å ¨åÂÂè½ORM;
- å ³èÂÂ(å å«ä¸Â个ï¼Âå å«å¤Â个ï¼Âå±ÂäºÂï¼Âå¤Â对å¤Âï¼Âå¤Âç§Âå å«);
- Callbacks(Ã¥ÂÂ建/ä¿ÂÃ¥ÂÂ/æ´æ°/å é¤/æÂ¥æ¾ä¹ÂÃ¥ÂÂ/ä¹ÂÃ¥ÂÂ);
- é¢Âå 载;
- äºÂå¡
- å¤ÂÃ¥ÂÂ主é®
- SQL Builder
- èªå¨è¿Â移
- æÂ¥å¿Â
- å¯æ©å±Âï¼Âç¼ÂÃ¥ÂÂåºäºÂGORMÃ¥ÂÂè°ÂçÂÂæÂÂ件
- æ¯Â个åÂÂè½é½æÂÂæµÂè¯Â
- å¼ÂÃ¥ÂÂ人åÂÂÃ¥ÂÂ好
å¿«éÂÂå¯å¨
å®Â裠ä¸Âè¿ÂæÂ¥ï¼Â
go get github.com/jinzhu/gorm
è¿ÂæÂÂ¥ MySQL æ°æ®åºÂï¼Â
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"time"
)
func main() {
// Ã¥ÂÂè https://github.com/go-sql-driver/mysql#dsn-data-source-name è·åÂÂ详æÂÂ
//dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
//db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
db, err := gorm.Open(mysql.New(mysql.Config{
DSN: "root:123456@tcp(192.168.168.101:3306)/gorm?charset=utf8&parseTime=True&loc=Local", // DSN data source name
DefaultStringSize: 256, // string ç±»åÂÂÃ¥ÂÂ段çÂÂé»Â认é¿度
DisableDatetimePrecision: true, // ç¦Âç¨ datetime 精度ï¼ÂMySQL 5.6 ä¹ÂÃ¥ÂÂçÂÂæ°æ®åºÂä¸Âæ¯æÂÂ
DontSupportRenameIndex: true, // éÂÂå½åÂÂç´¢å¼Âæ¶éÂÂç¨å é¤并æ°建çÂÂæ¹å¼Âï¼ÂMySQL 5.7 ä¹ÂÃ¥ÂÂçÂÂæ°æ®åºÂå MariaDB ä¸Âæ¯æÂÂéÂÂå½åÂÂç´¢å¼Â
DontSupportRenameColumn: true, // ç¨ `change` éÂÂå½åÂÂÃ¥ÂÂï¼ÂMySQL 8 ä¹ÂÃ¥ÂÂçÂÂæ°æ®åºÂå MariaDB ä¸Âæ¯æÂÂéÂÂå½åÂÂÃ¥ÂÂ
SkipInitializeWithVersion: false, // æ ¹æ®å½Âå MySQL çÂÂ揪å¨éÂ
Âç½®
}), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
// ----------------------------æ°æ®åºÂè¿Âæ¥池----------------------------
sqlDB, err := db.DB()
// SetMaxIdleConns 设置空é²è¿Âæ¥池ä¸Âè¿ÂæÂ¥çÂÂæÂÂ大æ°éÂÂ
sqlDB.SetMaxIdleConns(10)
// SetMaxOpenConns 设置æÂÂå¼Âæ°æ®åºÂè¿ÂæÂ¥çÂÂæÂÂ大æ°éÂÂãÂÂ
sqlDB.SetMaxOpenConns(100)
// SetConnMaxLifetime 设置äºÂè¿ÂæÂ¥å¯å¤Âç¨çÂÂæÂÂ大æ¶é´ãÂÂ
sqlDB.SetConnMaxLifetime(time.Hour)
fmt.Println("success to link mysql")
select {}
}
注æÂÂï¼ æ³è¦Âæ£确çÂÂå¤ÂçÂÂàtime.Time
àï¼Âæ¨éÂÂè¦Â带ä¸ÂàparseTime
àåÂÂæ°@(æ´å¤ÂÃ¥ÂÂæ°) è¦Âæ¯æÂÂå®Âæ´ç UTF-8 ç¼Âç Âï¼Âæ¨éÂÂè¦Âå°Âàcharset=utf8
àæ´æ¹为àcharset=utf8mb4
ÃÂ
MySQL é«Â级é Âç½®ï¼Â
db, err := gorm.Open(mysql.New(mysql.Config{
DSN: "gorm:gorm@tcp(127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local", // DSN data source name
DefaultStringSize: 256, // string ç±»åÂÂÃ¥ÂÂ段çÂÂé»Â认é¿度
DisableDatetimePrecision: true, // ç¦Âç¨ datetime 精度ï¼ÂMySQL 5.6 ä¹ÂÃ¥ÂÂçÂÂæ°æ®åºÂä¸Âæ¯æÂÂ
DontSupportRenameIndex: true, // éÂÂå½åÂÂç´¢å¼Âæ¶éÂÂç¨å é¤并æ°建çÂÂæ¹å¼Âï¼ÂMySQL 5.7 ä¹ÂÃ¥ÂÂçÂÂæ°æ®åºÂå MariaDB ä¸Âæ¯æÂÂéÂÂå½åÂÂç´¢å¼Â
DontSupportRenameColumn: true, // ç¨ `change` éÂÂå½åÂÂÃ¥ÂÂï¼ÂMySQL 8 ä¹ÂÃ¥ÂÂçÂÂæ°æ®åºÂå MariaDB ä¸Âæ¯æÂÂéÂÂå½åÂÂÃ¥ÂÂ
SkipInitializeWithVersion: false, // æ ¹æ®å½Âå MySQL çÂÂ揪å¨éÂ
Âç½®
}), &gorm.Config{})
GORM Ã¥Â
Â许éÂÂè¿ÂàDriverName
àéÂÂ项èªå®Âä¹ MySQL 驱å¨ï¼Âä¾Âå¦Âï¼Â
import (
_ "example.com/my_mysql_driver"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
db, err := gorm.Open(mysql.New(mysql.Config{
DriverName: "my_mysql_driver",
DSN: "gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True&loc=Local", // data source name, 详æÂÂ
Ã¥ÂÂèÂÂï¼Âhttps://github.com/go-sql-driver/mysql#dsn-data-source-name
}), &gorm.Config{})
GORM Ã¥Â
Â许éÂÂè¿Âä¸Â个ç°æÂÂçÂÂæ°æ®åºÂè¿ÂæÂ¥æÂ¥åÂÂå§ÂÃ¥ÂÂàgorm.DB
import (
"database/sql"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
sqlDB, err := sql.Open("mysql", "mydb_dsn")
gormDB, err := gorm.Open(mysql.New(mysql.Config{
Conn: sqlDB,
}), &gorm.Config{})
表æ°æ®æÂÂä½Âï¼Âå¢Âå æ¹æÂÂ¥
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type User struct {
Id int
Name string
Age int
Addr string
Pic string
}
func main() {
dsn := "root:root123\@tcp(127.0.0.1:3306)/test\_gorm?charset=utf8mb4\&parseTime=True\&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), \&gorm.Config{})
if err != nil {
panic(err)
}
// èªå¨è¿Â移
db.Set("gorm:table\_options", "ENGINE=InnoDB").AutoMigrate(\&User{})
// å¢Â
db.Create(&User{
Name: "å¼ ä¸Â",
Age: 18,
Addr: "Ã¥ÂÂ京å¸Â",
Pic: "/static/img.png",
})
// æÂÂ¥
var user User
db.First(&user)
fmt.Println(user) // {1 张丠18 Ã¥ÂÂ京帠/static/img.png}
// æ¹
user.Name = "lisi"
db.Save(&user)
fmt.Println(user) // {1 lisi 18 Ã¥ÂÂ京帠/static/img.png}
// Ã¥ÂÂ
db.Delete(&user)
}
模åÂÂå®Âä¹Â:
模åÂÂÃ¥ÂÂÃ¥ÂÂ表åÂÂçÂÂæ å°Â堳系
è§ÂÃ¥ÂÂï¼Â
- 第ä¸Â个大åÂÂÃ¥ÂÂæ¯ÂÃ¥ÂÂ为å°ÂÃ¥ÂÂ;
- éÂÂå°堶ä»Â大åÂÂÃ¥ÂÂæ¯ÂÃ¥ÂÂ为å°ÂÃ¥ÂÂ并ä¸Âå¨åÂÂé¢å ä¸ÂÃ¥ÂÂ线;
- è¿ÂçÂÂçÂÂå 个大åÂÂÃ¥ÂÂæ¯Âï¼ÂåªæÂÂ第ä¸Â个éµ循ä¸Âé¢çÂÂ两æ¡è§ÂÃ¥ÂÂï¼Âå ¶ä»ÂçÂÂ大åÂÂÃ¥ÂÂæ¯Â转为å°ÂÃ¥ÂÂï¼Âä¸Âå ä¸ÂÃ¥ÂÂ线ï¼ÂéÂÂå°å°ÂÃ¥ÂÂï¼ÂÃ¥ÂÂé¢çÂÂ第ä¸Â个大åÂÂÃ¥ÂÂæ¯ÂÃ¥ÂÂå°ÂÃ¥ÂÂ并å ä¸ÂÃ¥ÂÂ线;
- å¤Âæ°形å¼Â;
举ä¾Âï¼Â
- User => users é¦ÂÃ¥ÂÂæ¯Âå°ÂÃ¥ÂÂï¼Âå¤Âæ°
- UserInfo => user_infos
- DBUserInfo => db_user_infos
- DBXXXXUserInfo => dbxxxx_user_infos
ç»ÂæÂÂä½ÂÃ¥ÂÂ段åÂÂÃ¥ÂÂÃ¥ÂÂÃ¥ÂÂçÂÂ对åºÂè§ÂÃ¥ÂÂ
è§Âå * Ã¥ÂÂÃ¥ÂÂæ¯åÂÂ段åÂÂçÂÂèÂÂå½¢å°ÂÃ¥ÂÂ
举ä¾Â
- Name –> name
- CreatedTime –> create_time
å¯以éÂÂè¿Âgormæ Âç¾æÂÂå®ÂÃ¥ÂÂÃ¥ÂÂï¼ÂAnimalId int64ÃÂgorm:"column:beast_id"
gorm.Model
åºæ¬模åÂÂå®Âä¹Âgorm.Modelï¼Âå æÂŒÂÂ段 IDï¼ÂCreatedAtï¼ÂUpdatedAtï¼ÂDeletedAt
Ã¥ÂÂæ°说æÂÂï¼Â
- IDï¼Â主é®èªå¢Âé¿;
- CreatedAtï¼Âç¨äºÂÃ¥ÂÂå¨记å½ÂçÂÂÃ¥ÂÂ建æ¶é´;
- UpdatedAtï¼Âç¨äºÂÃ¥ÂÂå¨记å½ÂçÂÂä¿®æ¹æ¶é´;
- DeletedAtï¼Âç¨äºÂÃ¥ÂÂå¨记å½ÂçÂÂå é¤æ¶é´;
åªéÂÂè¦Âå¨èª己çÂÂ模åÂÂä¸ÂæÂÂå®Âgorm.Modelå¿åÂÂÃ¥ÂÂ段ï¼Âå³å¯使ç¨ä¸Âé¢çÂÂÃ¥ÂÂ个åÂÂ段
gorm.Model.go
package gorm
import "time"
// Model a basic GoLang struct which includes the following fields: ID, CreatedAt, UpdatedAt, DeletedAt
// It may be embedded into your model or you may build your own model without it
// type User struct {
// gorm.Model
// }
type Model struct {
ID uint `gorm:"primarykey"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt DeletedAt `gorm:"index"`
}
// æ·»å åÂÂ段 `ID`, `CreatedAt`, `UpdatedAt`, `DeletedAt`
type User struct {
gorm.Model
Name string
}
é«Â级éÂÂ项
ç»ÂæÂÂä½Âæ Âç¾gormçÂÂ使ç¨:
type User struct {
Name string `gorm:"<-:create"` // Ã¥Â
Â许读åÂÂÃ¥ÂÂ建
Name string `gorm:"<-:update"` // Ã¥Â
Â许读åÂÂæ´æ°
Name string `gorm:"<-"` // Ã¥Â
Â许读åÂÂÃ¥ÂÂï¼ÂÃ¥ÂÂ建åÂÂæ´æ°ï¼Â
Name string `gorm:"<-:false"` // Ã¥Â
Â许读ï¼Âç¦Âæ¢åÂÂ
Name string `gorm:"->"` // åª读ï¼Âé¤éÂÂæÂÂèªå®Âä¹ÂéÂ
Âç½®ï¼Âå¦åÂÂç¦Âæ¢åÂÂï¼Â
Name string `gorm:"->;<-:create"` // Ã¥Â
Â许读åÂÂÃ¥ÂÂ
Name string `gorm:"->:false;<-:create"` // ä»Â
Ã¥ÂÂ建ï¼Âç¦Âæ¢仠db 读ï¼Â
Name string `gorm:"-"` // 读åÂÂæÂÂä½ÂÃ¥ÂÂä¼Â忽ç¥该åÂÂ段
}
Ã¥ÂÂ建/æ´æ°æ¶é´追踪ï¼Â纳ç§ÂãÂÂ毫ç§ÂãÂÂç§ÂãÂÂTimeï¼Â:
GORM 约å®Â使ç¨ CreatedAtãÂÂUpdatedAt 追踪åÂÂ建/æ´æ°æ¶é´ãÂÂå¦ÂæÂÂæ¨å®Âä¹ÂäºÂè¿Âç§ÂÃ¥ÂÂ段ï¼ÂGORM å¨åÂÂ建ãÂÂæ´æ°æ¶ä¼Âèªå¨填堠å½ÂÃ¥ÂÂæ¶é´
è¦Â使ç¨ä¸ÂÃ¥ÂÂÃ¥ÂÂ称çÂÂÃ¥ÂÂ段ï¼Âæ¨å¯以éÂ
Âç½® autoCreateTimãÂÂautoUpdateTim æ Âç¾
å¦ÂæÂÂæ¨æ³è¦Âä¿Âå UNIXï¼Â毫/纳ï¼Âç§Âæ¶é´æ³ï¼ÂèÂÂä¸Âæ¯ timeï¼Âæ¨åªéÂÂç®ÂÃ¥ÂÂå°尠time.Time ä¿®æ¹为 int å³å¯
type User struct {
CreatedAt time.Time // å¨åÂÂ建æ¶ï¼Âå¦ÂæÂÂ该åÂÂ段å¼为é¶å¼ï¼ÂÃ¥ÂÂ使ç¨å½ÂÃ¥ÂÂæ¶é´填åÂ
Â
UpdatedAt int // å¨åÂÂ建æ¶该åÂÂ段å¼为é¶å¼æÂÂèÂÂ
å¨æ´æ°æ¶ï¼Â使ç¨å½ÂÃ¥ÂÂæ¶é´æ³ç§Âæ°填åÂ
Â
Updated int64 `gorm:"autoUpdateTime:nano"` // 使ç¨æ¶é´æ³填纳ç§Âæ°åÂ
Â
æ´æ°æ¶é´
Updated int64 `gorm:"autoUpdateTime:milli"` // 使ç¨æ¶é´æ³毫ç§Âæ°填åÂ
Â
æ´æ°æ¶é´
Created int64 `gorm:"autoCreateTime"` // 使ç¨æ¶é´æ³ç§Âæ°填åÂ
Â
Ã¥ÂÂ建æ¶é´
}
Ã¥ÂÂ段æ Âç¾
声æ model æ¶ï¼Âtag æ¯å¯éÂÂçÂÂï¼ÂGORM æ¯æÂÂ以丠tagï¼ tag Ã¥ÂÂ大å°ÂÃ¥ÂÂä¸ÂæÂÂæÂÂï¼Âä½Â建议使ç¨ camelCase é£Âæ ¼ï¼Âä¹Âå°±æ¯驼峰àcamelCase
àå½åÂÂé£Âæ ¼ãÂÂå¤Â个å±Âæ§å¼ä¹Âé´ç¨åÂÂå·åÂÂéÂÂ(è±æÂÂçÂÂ;):gorm:"size:64;not null"
æ¡Âä¾Â
package main
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"log"
"os"
"time"
)
type User struct {
UserId uint `gorm:"primaryKey"`
Name string `gorm:"column:user_name;type:varchar(60)"`
Gender uint `gorm:"index"`
}
func main() {
// æÂ¥å¿ÂéÂ
Âç½®
newLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writerï¼ÂæÂ¥å¿Âè¾ÂåºçÂÂç®æ Âï¼ÂÃ¥ÂÂç¼ÂÃ¥ÂÂæÂ¥å¿ÂÃ¥ÂÂ
å«çÂÂÃ¥ÂÂ
容âÂÂâÂÂè¯ÂèÂÂ
注ï¼Â
logger.Config{
SlowThreshold: time.Second, // æÂ
¢ SQL éÂÂå¼
LogLevel: logger.Info, // æÂ¥å¿Â级å«为info
IgnoreRecordNotFoundError: true, // 忽çÂÂ¥ErrRecordNotFoundï¼Âè®°å½Âæªæ¾å°ï¼ÂéÂÂ误
Colorful: true, // 彩è²æÂÂå°
},
)
dsn := "root:123@tcp(127.0.0.1:3306)/gorm_test?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: newLogger,
})
if err != nil {
panic(err) // å¦ÂæÂÂæ°æ®åºÂä¸ÂÃ¥ÂÂå¨ä¼ÂæÂ¥éÂÂ
}
db.AutoMigrate(&User{})
// å¦ÂæÂÂ表ä¹ÂÃ¥ÂÂÃ¥ÂÂå¨ä¼Âä¿®æ¹ï¼Âä½Âæ¯åªä¼Âä¿®æ¹ä¹ÂÃ¥ÂÂÃ¥ÂÂå¨çÂÂÃ¥ÂÂ段çÂÂå±Âæ§ï¼Âæ æ³Âè¯Âå«å é¤åÂÂ段
}
æ»ç»Â
æ¾ÂÂ主è¦Âä»Âç»Â亠GORM æ¡Âæ¶çÂÂç¸堳åºç¡ÂçÂ¥è¯Âï¼Âä»Âç»ÂäºÂ常ç¨çÂÂæÂ¥å£å½æ°ï¼Âå ·ä½ÂçÂÂç»ÂèÂÂè¿Âæ¯éÂÂè¦Âä»Âç»Âç Â究å®Âæ¹æÂÂæ¡£ãÂÂè¿Âä¸Â个æ¡Âæ¶çÂÂå¦习é½å¯以çÂÂåºå®Âæ¹æÂÂæ¡£çÂÂéÂÂè¦Âæ§ï¼ÂÃ¥ÂÂæ¶å¦习æ¡Âæ¶è¿Âæ¯è¦Âå¤Âä¸ÂæÂÂç»Âä¹ æÂÂè¡ÂãÂÂ