1. Getting Started with GORM
1.1 What is ORM ?
- The full English name of orm is object relational mapping, which is the object mapping relationship.
- Simply put, everything is an object in an object-oriented program like python , but the databases we use are all relational
- In order to ensure consistent usage habits, the object model of the programming language and the relational model of the database are mapped through orm , so that we can directly use the object model of the programming language to operate the database instead of directly using the sql language
Using the orm framework of golang is to map the struct in golang, that is, the structure and the table fields in the database. That is to say, operating the database is not directly operating the database, but through the structure. Of course, the database-related sdk is used here.
All in all, you can operate the database by manipulating the structure, and by manipulating the structure, the data in the table will actually change accordingly.
The main function of the orm framework is that it is a struct in go, and it is actually a class in java, that is, to create a mapping relationship between objects and tables. We don't need to operate the table, just operate the object directly.
1.2 What is GORM ?
- Full-featured ORM ( almost all features included )
- Model association ( one-to-one, one-to-many, one-to-many (reverse), many-to-many, polymorphic association )
- 钩子 (Before/After Create/Save/Update/Delete/Find)
- Preloading
- affairs
- composite primary key
- SQL constructor
- automatic migration
- log
- Writing extensible plugins based on GORM callbacks
- Full Feature Test Coverage
- developer friendly
1.3 Basic use of GORM (v2)
go get -u gorm.io/gorm
2. Connect to MySQL
Create a database first
mysql> create database test_db charset utf8; # 创建数据库
mysql> use test_db; # 切换到数据库
mysql> show tables; # 查看是否生成表
+-------------------+
| Tables_in_test_db |
+-------------------+
| users |
+-------------------+
mysql> desc users; # 查看表的字段是否正常
+----------+------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+------------+------+-----+---------+----------------+
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| username | longtext | YES | | NULL | |
| password | longtext | YES | | NULL | |
+----------+------------+------+-----+---------+----------------+
If the imported package is not used, add _ in front, such as
import _"gorm.io/driver/mysql"
Why import it if you don't use this package? When I import it and don't use it, it means that the init function in the package is to be executed. In fact, it is to execute the init inside.
parseTime parsing time: Gorm comes with some creation time, update time, and deletion time. When doing the mapping relationship, it is a time object when it is obtained, and it will be automatically converted into a time object here.
loc=Local: use a time zone of the local environment
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func main() {
dsn := "root:7PXjAkY!&nlR@tcp(192.168.11.128:3306)/test_db?charset=utf8mb4&parseTime=True&loc=Local"
//这是固定写法
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic(err)
}
fmt.Println(db)
}
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type User struct {
Id int64 `gorm:"primary_key" json:"id"`
Username string
Password string
}
func main() {
dsn := "root:7PXjAkY!&nlR@tcp(192.168.11.128:3306)/test_db?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
fmt.Println(err)
}
//自动迁移
err = db.AutoMigrate(User{})
if err != nil {
fmt.Println(err)
}
}
mysql> show tables;
+-------------------+
| Tables_in_test_db |
+-------------------+
| users |
+-------------------+
1 row in set (0.00 sec)
mysql> desc users;
+----------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+----------+------+-----+---------+----------------+
| id | bigint | NO | PRI | NULL | auto_increment |
| username | longtext | YES | | NULL | |
| password | longtext | YES | | NULL | |
+----------+----------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
4. Basic CRUD
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
//自定义返回表名
func (* User) TableName() string {
return "user"
}
// User 表的结构体ORM映射
type User struct {
Id int64 `gorm:"primary_key" json:"id"`
Username string
Password string
}
func main() {
// 0、连接数据库
dsn := "root:1@tcp(127.0.0.1:3306)/test_db?
charset=utf8mb4&parseTime=True&loc=Local"
db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{})
db.AutoMigrate(User{})
// 1、增
db.Create(&User{
//Id: 3,
Username: "zhangsan",
Password: "123456",
})
// 2、改
db.Model(User{Id: 3,}).Update("username", "lisi")
//db.Model(User{}).Where("id = 1").Update("username", "lisi")
// 3、查
// 3.1 过滤查询
u := User{Id: 3}
db.First(&u)
fmt.Println(u)
// 3.2 查询所有数据
users := []User{}
db.Find(&users)
fmt.Println(users) // [{2 zhangsan 123456} {3 lisi 123456}]
// 4、删
// 4.1 删除 id = 3 的用户
db.Delete(&User{Id: 3})
// 4.2 条件删除
db.Where("username = ?", "zhangsan").Delete(&User{})
}
All the structures used above are related to that table.
Query all data.
var users []User
db.Find(&users)
fmt.Println(users)
2. Model definition
Reference document: https://gorm.io/zh_CN/docs/models.html
The id here is actually a primary key, and the primary key can be auto-incremented and cannot be repeated.
The above are directly restricted in the database.