GORM简介
- ORM 即Object Relational Mapping,对象关系映射。Relational 指各种SQL 类的关系型数据库。Object 指面向对象编程(object-oriented programming)中的对象。ORM 在数据库记录和程序对象之间做一层映射转换,使程序中不用再去编写原生SQL,而是面向对象的思想去编写类、对象、调用相应的方法来完成数据库操作。
go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql
- GORM 是一个全能的、友好的、基于golang 的ORM 库。
- GORM 倾向于约定,而不是配置。默认情况下,GORM 使用ID 作为主键,使用结构体名的【蛇形复数】作为表名,字段名的【蛇形】(小写+下划线分隔)作为列名,并使用CreatedAt 、UpdatedAt 字段追踪创建、更新时间。
- GORM 完全是在操作Struct ,看不到SQL 的影子。
- GORM 同时支持使用函数链的方式写SQL 语句。
GORM 库操作
- 连接数据库
dsn := "tester:123456@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
- 结构体
type Student struct {
Id int `gorm:"column:id;primaryKey"`
Name string `gorm:"column:name"`
Province string
City string `gorm:"column:city"`
Address string `gorm:"column:addr"`
Score float32 `gorm:"column:score"`
Enrollment time.Time `gorm:"column:enrollment;type:date"`
}
func (Student) TableName() string {
return "student"
}
- 插入
func create(db *gorm.DB) {
student := Student{Name: "光绪", Province: "北京", City: "北京", Score: 38, Enrollment: time.Now()}
db.Create(&student)
students := []Student{{Name: "无极", Province: "北京", City: "北京", Score: 38, Enrollment: time.Now()}, {Name: "小王", Province: "上海", City: "上海", Score: 12, Enrollment: time.Now()}, {Name: "小亮", Province: "北京", City: "北京", Score: 20, Enrollment: time.Now()}}
db.Create(students)
students = []Student{{Name: "大壮", Province: "北京", City: "北京", Score: 38, Enrollment: time.Now()}, {Name: "刘二", Province: "上海", City: "上海", Score: 12, Enrollment: time.Now()}, {Name: "文明", Province: "北京", City: "北京", Score: 20, Enrollment: time.Now()}}
db = db.CreateInBatches(students, 2)
fmt.Printf("insert %d rows\n", db.RowsAffected)
}
- 更新
func update(db *gorm.DB) {
db.Model(&Student{}).Where("city=?", "北京").Update("score", 10)
db.Model(&Student{}).Where("city=?", "北京").Updates(map[string]interface{}{"score": 3, "addr": "海淀区"})
student := Student{Id: 2, City: "太原"}
db = db.Model(&student).Where("city=?", "郑州").Updates(map[string]interface{}{"score": 10, "addr": "中原区"})
fmt.Printf("update %d rows\n", db.RowsAffected)
}
- 查询
func print(students []Student){
for _, ele := range students {
fmt.Printf("id=%d, name=%s\n", ele.Id, ele.Name)
}
fmt.Println()
}
func query(db *gorm.DB) {
var student Student
db.Where("city=?", "郑州").First(&student)
fmt.Println(student.Name)
fmt.Println()
var students []Student
db.Where("city=?", "郑州").Find(&students)
print(students)
students = []Student{}
db.Where("city in ?", []string{"郑州", "北京"}).Find(&students)
print(students)
fmt.Println("============where end============")
student = Student{}
students = []Student{}
db.First(&student, 1)
fmt.Println(student.Name)
fmt.Println()
db.Find(&students, []int{1, 2, 3})
print(students)
fmt.Println("============primary key end============")
student = Student{}
students = []Student{}
db.Where(map[string]interface{}{"city": "郑州", "score": 0}).Find(&students)
print(students)
fmt.Println("============map end============")
student = Student{}
students = []Student{}
db.Where("city=?", "郑州").Or("city=?", "北京").Order("score").Limit(1).Offset(0).Find(&students)
print(students)
fmt.Println("============limit end============")
student = Student{}
db.Select("name").Take(&student)
fmt.Printf("name=%s, province=%s\n", student.Name, student.Province)
fmt.Println("============select specified column end============")
}
- 删除
func delete(db *gorm.DB) {
db = db.Where("city in ?", []string{"常州", "成都"}).Delete(&Student{})
fmt.Printf("delete %d rows\n", db.RowsAffected)
db = db.Delete(&Student{}, 27)
fmt.Printf("delete %d rows\n", db.RowsAffected)
db = db.Delete(&Student{}, []int{28, 29, 30})
fmt.Printf("delete %d rows\n", db.RowsAffected)
}
- 事务
type Tx interface {
Commit() error
Rollback() error
}
func transaction(db *gorm.DB) {
tx := db.Begin()
defer tx.Rollback()
for i := 0; i < 10; i++ {
student := Student{Name: "学生" + strconv.Itoa(i), Province: "北京", City: "北京", Score: 38, Enrollment: time.Now()}
if err := tx.Create(&student).Error; err != nil {
return
}
}
tx.Commit()
}