[gin learning notes] 07 get to know grom and use Gorm for database operation

Time:2022-5-3

This article learning video https://www.bilibili.com/video/BV1Bz411v78U/?spm_id_from=333.788

Chinese Gorm official document https://jasperxu.com/Programming/Golang/GORM/
Another document https://learnku.com/docs/gorm/v2/index/9728

What is ORM

  • An auxiliary tool for database operation
  • Map between our go structure and the database, so that we can intuitively reflect the relationship of the database and the content of the table on the structure
  • You can add, delete, modify and query by using the structure

How to connect to the database

  1. Introduce Gorm package GitHub com/jinzhu/gorm
  2. Introduce MySQL driver package GitHub com/go-sql-driver/mysql
  3. Establish a database connection for the first time. The code is as follows
package main

import (
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
)

func main() {
	db, err := gorm.Open("mysql",
		"root:[email protected]/ginclass?charset=utf8mb4&parseTime=True&loc=Local")
	defer db.Close()

	if err != nil {
		panic(err)
	}
}

Creating tables with grom

Use dB Automigrate to create a table. Description: dB Automigrate will automatically determine whether the table exists. If it does not exist, create a table.

package main

import (
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
)

type HelloWorld struct {
	gorm.Model
	Name string
	Sex  bool
	Age  int
}

func main() {
	db, err := gorm.Open("mysql",
		"root:[email protected]/ginclass?charset=utf8mb4&parseTime=True&loc=Local")
	defer db.Close()

	if err != nil {
		panic(err)
	}
	//db. Automigrate determines whether a table exists. If it does not exist, it will be created automatically
	db.AutoMigrate(&HelloWorld{})
}

Gorm. In the HelloWorld structure Model is a golang structure that contains four fields: ID, createdat, updatedat and deletedat. These fields will be created automatically when creating a table.
The structure after table building is as follows
[gin learning notes] 07 get to know grom and use Gorm for database operation
After the basic operations of adding and deleting tables are completed.

Increase operation

Use dB Create to create a piece of data whose name is Kaka, sex is true and age is 21

package main

import (
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
)

type HelloWorld struct {
	gorm.Model
	Name string
	Sex  bool
	Age  int
}

func main() {
	db, err := gorm.Open("mysql",
		"root:[email protected]/ginclass?charset=utf8mb4&parseTime=True&loc=Local")
	defer db.Close()
	if err != nil {
		panic(err)
	}
	//db. Automigrate determines whether a table exists. If it does not exist, it will be created automatically
	db.AutoMigrate(&HelloWorld{})
	//Create data
	db.Create(&HelloWorld{
		Name: "kaka",
		Sex:  true,
		Age:  21,
	})
}

After running, you can see that there is one more piece of data in the table.
[gin learning notes] 07 get to know grom and use Gorm for database operation
Let’s create two pieces of data to check.

Check operation

  1. db. First method use
    We use dB First, check the first data in the database
    [gin learning notes] 07 get to know grom and use Gorm for database operation
    The results after operation are as follows
    [gin learning notes] 07 get to know grom and use Gorm for database operation
    Specify criteria for query
    [gin learning notes] 07 get to know grom and use Gorm for database operationThe query results are as follows
    [gin learning notes] 07 get to know grom and use Gorm for database operation
  2. db. Find method usage
    Note: dB When you find, you should accept the address of a slice
    The code is as follows
    [gin learning notes] 07 get to know grom and use Gorm for database operation
    The printing results are as follows
    [gin learning notes] 07 get to know grom and use Gorm for database operation
    You can see that without conditions, DB Find found all the results.
    We add the condition where sex = false to query
    The code is as follows
    [gin learning notes] 07 get to know grom and use Gorm for database operationgive the result as follows
    [gin learning notes] 07 get to know grom and use Gorm for database operation
    Generally, in the actual development process, where will be written in the front. The example is as follows
    [gin learning notes] 07 get to know grom and use Gorm for database operation
    The or statement is relatively simple and can be written in where or dB where(). Or. Find()

Change operation

db. Update() to modify a single field
Change the value of the name field in the data with ID 1 in the HelloWorld table to Jack
The code is as follows
[gin learning notes] 07 get to know grom and use Gorm for database operation
db. Updates() to modify multiple fields
[gin learning notes] 07 get to know grom and use Gorm for database operation
If there is an empty attribute in updates (HelloWorld {}), such as age = 0, name = “”, or sex = false, these fields will not be modified.

If you want to change the field to these empty attributes, such as changing age to 0, you need to add a map
The code is as follows
[gin learning notes] 07 get to know grom and use Gorm for database operation
If you want to modify multiple pieces of data, such as ID in 1 and 2, change them
The code is as follows
[gin learning notes] 07 get to know grom and use Gorm for database operation
Note that slices should be added to the first method

Delete operation

Use dB Delete method
[gin learning notes] 07 get to know grom and use Gorm for database operation
However, this deletion is a soft deletion, as shown in the figure below
[gin learning notes] 07 get to know grom and use Gorm for database operation
Delete the data with ID 1 and 2. The code is as follows
[gin learning notes] 07 get to know grom and use Gorm for database operation
This is also a soft deletion. If you want to make a hard deletion, you need to add the unscoped () method
The code is as follows
[gin learning notes] 07 get to know grom and use Gorm for database operation

summary

  • Create connection
    • db, err := gorm.Open(“mysql”,
      “root:[email protected]/ginclass?charset=utf8mb4&parseTime=True&loc=Local”)
      defer db.Close()
  • Build table
    • First define a structure, such as HelloWorld
    • Then dB Automigrate (& HelloWorld {}) to create tables
  • Increase operation
    • db.Create(&HelloWorld{
      Name: “kaka”,
      Sex: true,
      Age: 21,
      })
    • &HelloWorld {} indicates which table to specify
  • Check operation
    • db. First() to check the first data in the database
    • db. Add where in first() to find conditions
    • db. Find(), and a structure slice needs to be specified in the method
    • db.Where.Find()
  • Change operation
    • db. Update() modifies a single field of a single piece of data
    • db. Updates() modifies multiple fields of a single piece of data
    • db. Updates() method to change the field to 0 value, such as false, number 0 and empty string
    • db. Updates() method for modifying multiple pieces of data
  • Delete operation
    • db. Delete() soft delete
    • db. Where(). Unscoped(). Delete() hard delete