📚 介绍
GORM是Go的一个极好的ORM(Object Relational Mapping)对象关系映射框架,开发者友好,即我们通常说的数据持久层框架或者是数据库框架。
特性:
-
全功能 ORM
-
关联 (Has One,Has Many,Belongs To,Many To Many,多态,单表继承)
-
Create,Save,Update,Delete,Find 中钩子方法
-
支持
Preload
、Joins
的预加载 -
事务,嵌套事务,Save Point,Rollback To Saved Point
-
Context、预编译模式、DryRun 模式
-
批量插入,FindInBatches,Find/Create with Map,使用 SQL 表达式、Context Valuer 进行 CRUD
-
SQL 构建器,Upsert,数据库锁,Optimizer/Index/Comment Hint,命名参数,子查询
-
复合主键,索引,约束
-
Auto Migration
-
自定义 Logger
-
灵活的可扩展插件 API:Database Resolver(多数据库,读写分离)、Prometheus…
-
每个特性都经过了测试的重重考验
-
开发者友好
这里我们仅仅介绍框架的基本使用。
📋 数据库连接
连接数据库。
// mysql连接串
dsn := "username:password@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
其中username
和password
置换成自己数据库连接用户名和密码。
📁 模型定义
在Go中模型用struct定义,如:
type Product struct {
gorm.Model //内嵌模型
Code string
Price uint
}
其中gorm.Model
属于内嵌模型,模型定义为
// gorm.Model 的定义
type Model struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt gorm.DeletedAt `gorm:"index"`
}
声明了模型接下来就是我们熟悉的增删改查操作。
📘 创建
往数据库增加插入一条记录。
result := db.Create(&Products{Code:"D22", Price:200})
fmt.Println(result)
效果截图:
📕 查询
查询数据库数据。
var productsRes []Products
result := db.Where("code = ?", "D22").Find(&productsRes)
if result.Error == nil{
fmt.Println(productsRes)
}
查询结果截图:
📒 更新
条件更新单条数据:
var productsRes []Products
result := db.Where("code = ?", "D22").Find(&productsRes)
if result.Error == nil{
fmt.Println(productsRes)
}
db.Model(&Products{}).Where("code = ?", "D22").Update("price", 400)
result = db.Where("code = ?", "D22").Find(&productsRes)
if result.Error == nil{
fmt.Println(productsRes)
}
更新前后记录比对:
📓 删除
根据条件删除记录。
var productsRes []Products
result := db.Where("code = ?", "D22").Delete(&productsRes)
if result.Error == nil{
fmt.Println("记录删除成功!")
}
效果截图:
至此,Gorm连接mysql、记录的创建、查询、更新、删除我们都已经实现。关于GORM框架的详细介绍和更多好用功能大家可以关注GORM官方文档。
📖 三个链接
📢📢📢欢迎大家在公众号后台留言交流学习!!!📢📢📢
原文始发于微信公众号(fairy with you):go-gorm极好的ORM框架
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/29654.html