概述
- GORM是Golang目前比较热门的数据库ORM操作库,对开发者也比较友好,使用非常方便简单,使用上主要就是把struct类型和数据库表记录进行映射,操作数据库的时候不需要直接手写Sql代码
- GORM库github地址: https://github.com/go-gorm/gorm
- 关系型数据库都可适用(mysql/sqlite3/postgresql等)
依赖安装
go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql
数据库实操
初始化数据库
package test_gorm
import (
"gorm.io/gorm"
_ "gorm.io/gorm/dialects/sqlite"
)
var db *gorm.DB
func init() {
var err error
db, err = gorm.Open("sqlite3", "test.db")
db = db.Debug()
if err != nil {
panic(err)
}
sqlDB := db.DB()
sqlDB.SetMaxOpenConns(100)
sqlDB.SetMaxIdleConns(20)
}
func GetDB() *gorm.DB {
return db
}
建立数据库模型
package test_gorm
import "gorm.io/gorm"
type Food struct {
gorm.Model
Name string
Price float64
TypeId int
}
插入数据
package test_gorm
import (
"fmt"
)
func CreateFood() {
db.Create(&Food{
Price: 10.3,
Name: "ljc",
TypeId: 1,
})
fmt.Println("成功创建")
}
查询数据
package test_gorm
import (
"fmt"
)
func FirstFood() {
food := Food{}
db.First(&food)
fmt.Println("FirstFood-->", food)
}
func TakeFood() {
food := Food{}
db.Take(&food)
fmt.Println("TakeFood-->", food)
}
func ModelTake() {
food := Food{}
db.Model(Food{}).Take(&food)
fmt.Println("ModelTake-->", food)
}
func LastFood() {
food := Food{}
db.Last(&food)
fmt.Println("LastFood-->", food)
}
func FindFood(limit int) {
var foods []Food
db.Limit(limit).Find(&foods)
for index, food_ := range foods {
fmt.Println("FindFood-->", index, food_)
}
}
func Where() {
food := Food{}
db.Where("id == ?", 3).Take(&food)
fmt.Println("Where-->", food)
food_ := Food{}
food_.ID = 5
db.Where(&food_).Take(&food_)
fmt.Println("Where-->", food_)
}
func Select() {
food := Food{}
db.Model(food).Where("id == ?", 3).Select("name").Take(&food)
fmt.Println("Select-->", food)
}
func Count() {
var total int
db.Model(Food{}).Count(&total)
fmt.Println("Count-->", total)
}
更新数据
package test_gorm
import "fmt"
func WhereSave() {
food := Food{}
db.Model(food).Where("id == ?", 3).Take(&food)
food.Name = "ljc"
db.Save(&food)
fmt.Println("WhereSaveBefore-->", food)
food.Name = "jacklee"
db.Save(&food)
fmt.Println("WhereSaveAfter-->", food)
}
func WhereUpdates() {
updateFood := Food{
Name: "lijiacai",
Price: 1000000,
}
var food Food
sql := db.Model(Food{}).Where("id == ?", 5)
sql.Take(&food)
fmt.Println("WhereUpdatesBefore-->", food)
sql.Updates(&updateFood)
sql.Take(&food)
fmt.Println("WhereUpdatesAfter-->", food)
}
删除数据
package test_gorm
import "fmt"
func Delete() {
food := Food{}
db.Model(Food{}).Take(&food)
db.Model(Food{}).Where(&food).Delete(&food)
fmt.Println("Delete-->", food)
}
多表联查案例
package test_gorm
import "fmt"
type Topic struct {
gorm.Model
Title string
Content string
UserId int
User User `gorm:"foreignkey:UserId"`
}
type User struct {
gorm.Model
Name string
}
func (obj User) TableName() string {
return "user"
}
func (obj Topic) TableName() string {
return "topic"
}
func CreateUser() {
user := User{}
user.Name = "lijiacai"
db.Save(&user)
}
func CreateTopic() {
topic := Topic{}
topic.Title = "Alice dream"
topic.Content = "Yestoday,I will do ......."
topic.UserId = 1
db.Save(&topic)
}
func RalationSearch() {
topic := Topic{}
db.Model(Topic{}).Last(&topic)
fmt.Println("RalationSearch-->topic--", topic)
user := User{}
db.Model(&topic).Association("User").Find(&user)
fmt.Println("RalationSearch-->user--", user)
topic.User = user
fmt.Println("RalationSearch-->topic(user)--", topic)
}
type JoinRes struct {
Topic
User
}
func JoinSearch() {
var joinRes []JoinRes
err := db.Table("topic").Select("topic.*, user.*").Joins("left join user on topic.user_id=user.id").Find(&joinRes).Error
if err != nil {
fmt.Println(err)
}
fmt.Println("JoinSearch-->", joinRes[0].Title, joinRes[0].Name, joinRes[0].Content)
}
数据库事务
package test_gorm
import (
"errors"
"github.com/jinzhu/gorm"
)
func Transaction(tx *gorm.DB) error {
food := Food{}
food.Name = "zmj"
food.Price = 5
food.TypeId = 3
err := tx.Create(&food).Error
return err
}
func TransactionPanic(tx *gorm.DB) error {
food := Food{}
food.Name = "zmj"
food.Price = 88
food.TypeId = 88
err := tx.Create(&food).Error
err = errors.New("主动异常")
return err
}
执行
package main
import (
"casbin-go/test-gorm"
"fmt"
)
func TestFood() {
test_gorm.CreateFood()
test_gorm.FirstFood()
test_gorm.LastFood()
test_gorm.TakeFood()
test_gorm.FindFood(2)
test_gorm.Where()
test_gorm.ModelTake()
test_gorm.Select()
test_gorm.WhereSave()
test_gorm.WhereUpdates()
test_gorm.Delete()
test_gorm.Count()
test_gorm.GetDB().Transaction(test_gorm.Transaction)
test_gorm.LastFood()
err := test_gorm.GetDB().Transaction(test_gorm.TransactionPanic).Error()
fmt.Println(err)
test_gorm.LastFood()
}
func TestTopicUser() {
test_gorm.RalationSearch()
test_gorm.JoinSearch()
}
func main() {
test_gorm.GetDB().AutoMigrate(&test_gorm.Food{}, &test_gorm.User{}, &test_gorm.Topic{})
TestTopicUser()
}