Learning Notes on Golang Gin-Gorm
The article primarily explores the basics of GORM, various methods of database connection, and table creation. It's a study note compiled through learning from the GORM official Chinese documentation and Li Wenzhou's blog.
GORM is an ORM framework written in Go language. It boasts comprehensive documentation, user-friendliness, and support for mainstream databases. Object-Relational Mapping (ORM) refers to the mapping between relational databases and objects. Its purpose is to establish a mapping between relational databases and objects, thus eliminating the need to deal with complex SQL statements when operating databases. Instead, one can manipulate them as objects. (This article mainly uses MySQL database as an example, but examples for other databases can be found in the official documentation).
Official Chinese Documentation: [GORM Guide](https://gorm.io/zh_CN/docs/)
Below is the formal record of the learning process:
**Table of Contents:**
1. Features
2. Basic GORM Examples
3. Quickly Creating MySQL Instance with Docker
4. Creating a Database
5. Installation
6. Connecting to the Database
**Features:**
- Full-featured ORM
- Associations (Has One, Has Many, Belongs To, Many To Many, Polymorphism, Single Table Inheritance)
- Hooks methods in Create, Save, Update, Delete, Find
- Support for Preloading, Joins
- Transactions, Nested Transactions, Save Point, Rollback To Saved Point
- Context, Precompiled mode, DryRun mode
- Batch Insert, FindInBatches, Find/Create with Map, CRUD using SQL expressions, Context Valuer
- SQL Builder, Upsert, Database Lock, Optimizer/Index/Comment Hint, Named Parameters, Subqueries
- Composite Primary Key, Index, Constraint
- Auto Migration
- Custom Logger
- Flexible and Extensible Plugin API: Database Resolver (multi-database, read-write separation), Prometheus...
- Each feature has undergone rigorous testing
- Developer-friendly
**Basic GORM Examples:**
The article proceeds with connecting to the MySQL database.
If there's no MySQL database available, one can use Docker to quickly create a MySQL instance.
**Quickly Creating MySQL Instance with Docker:**
Prerequisite: Docker environment
Run a MySQL container environment named mysql8019 with root username and password root1234 on local port 13306:
```
docker run --name mysql8019 -p 13306:3306 -e MYSQL_ROOT_PASSWORD=root1234 -d mysql:8.0.19
```
Connect to the above MySQL environment using another MySQL client, with the password specified in the previous step, root1234:
```
docker run -it --network host --rm mysql mysql -h127.0.0.1 -P13306 --default-character-set=utf8mb4 -uroot -p
```
**Creating a Database:**
One can directly create a database using Navicat or SQLyog, or create it via command line (specific instructions below):
```
CREATE DATABASE dbname;
```
**Installation:**
```
go get -u gorm.io/gorm
go get -u gorm.io/driver/sqlite
```
**Connecting to the Database:**
For other databases, see the connection instructions in the official documentation.
import ( "gorm.io/driver/mysql" "gorm.io/gorm" ) func main() { 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{}) }
**Creating a Data Table (UserInfo):**
One can create the table in advance or use automatic migration to create it. Pay attention to the following points:
1. The structure name's first letter must be capitalized and correspond to the database table name.
2. The field names in the structure must start with a capital letter and correspond one-to-one with the fields in the database table.
3. A field named 'ID' will be automatically treated as the primary key. For other names, 'gorm:"primary_key"' should be added after them.
type UserInfo struct { ID uint Name string Gender string Hobby string } func (UserInfo) TableName() string { return "userinfo" }
If the data table is not created beforehand, add the following code after defining the structure:
db.AutoMigrate(&UserInfo{})
The table created automatically takes the plural form of the structure name. To disable the default plural form:
db.SingularTable(true)
To create a table named 'student' using the UserInfo structure:
db.Table("student").CreateTable(&UserInfo{})