ORM

One of the important layers of many back-end MVC frameworks, M layer (Model), is officially described as object relational mapping. Each database table has a corresponding model file to interact with the table. ORM method simplifies the native SQL statement, and makes it more convenient to use data caching and database transactions. Data table structure migration, etc., can save development time, let the project structure clear.

Gin

Gin is a Web framework based on GO. It has many advantages, such as flexibility, high performance, light weight and simplicity. Refer to the following documents:

Gin framework related documentation: Gin Git address, Gin Chinese documentation: gopher documentation

Gorm and mysql

Gin uses ORM, which requires a dedicated third-party package called GORM, and mysql if you use mysql for object mapping. Start by creating a folder named GinORM in the random file as the project folder. Go mod init GinORM to initialize the project (go.mod) :

go mod init GinORM
Copy the code

Then download these three packages:

go get  github.com/gin-gonic/gin
Copy the code
go get  github.com/jinzhu/gorm
Copy the code
go get  github.com/go-sql-driver/mysql
Copy the code

Create a new main.go file under GinORM to copy an official Gin example and import these three packages:

package main

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


func main(a) {
	r := gin.Default()
	r.GET("/ping".func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

Copy the code

Now running it directly will give an error because the compiler will notice that the package we imported is not yet used. Next prepare to connect to the database, first prepare a mysql database that can be used, and then write a struct mapping table of each field, field data type. For the time being, add a structure in main.go to allow you to use a single file in a single folder in a large project.

type User struct {
	ID   int    `gorm:"primary_key; AUTO_INCREMENT"` // Add the ID of the primary key. Gorm: How many types of tags can be inside? Type specifies the type of the column
	Name string `gorm:"size:215"`                   //Size the tag represents the column Size
	Age  int    `gorm:"type:smallint"`              //int type. Type can be specified
	Mail string `gorm:"type:varchar(256);" `
}

Copy the code

Alter table alter table alter table alter table alter table alter table

	/ / to add
	r.GET("/add".func(c *gin.Context) {
		for i := 0; i < 10; i++ {
			user := &User{Name: "robot_" + strconv.Itoa(i), Age: i, Mail: "qwe_" + strconv.Itoa(i) + "@qq.com"} // Note the variable type
			db.Create(&user)  // Insert data in pointer object mode, id is autoincrement primary key, do not set value
		}
		c.JSON(200, gin.H{
			"message": "Add 10 data completed",})})/ / delete
	r.GET("/del".func(c *gin.Context) {
		id, _ := strconv.Atoi(c.Query("id"))  // accept url parameter id, integer,
		delUser := &User{
			ID: id,     // where id = id
		}
		db.Delete(delUser)
		c.JSON(200, gin.H{
			"message": "Deletion completed",})})/ / change
	r.GET("/update".func(c *gin.Context) {
		id, _ := strconv.Atoi(c.Query("id"))
		name := c.Query("name")
		test := &User{
			ID: id,
		}
		db.Model(&test).Update("name", name)
		c.JSON(200, gin.H{
			"message": "Update successful",})})/ / check
	r.GET("/find".func(c *gin.Context) {
		var Result User
		name := c.Query("name")  // Accept the URL parameter name
		db.Debug().Where("name = ?", name).Find(&Result)  // If you add Debug() to db, the console will print native mysql.
		c.JSON(200, gin.H{
			"message": Result,
		})
	})

Copy the code

Use the AutoMigrate() method to automatically add fields and indexes that are not in the table. Gin main.go is very convenient to use, so you don’t need to run the migration manually.

db.AutoMigrate(&User{})
Copy the code

conclusion

The ORM function of Gin framework is implemented by GORM, which seems to have little correlation between the two. Gorm documents are also very simple, so you need to study by yourself when you encounter problems. There are very few materials on the Internet, and Gin feels similar to the feeling of Python’s Flask. Most functions rely on third-party packages, and finally present the complete code, the code has been tested, function is normal:

package main

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

type User struct {
	ID   int    `gorm:"primary_key; AUTO_INCREMENT"` // Add the ID of the primary key. Gorm: How many kinds of tags can be inside. Type Specifies the Type of the column
	Name string `gorm:"size:215"`                   //Size the tag represents the column Size
	Age  int    `gorm:"type:smallint"`              //int type. Type can be specified
	Mail string `gorm:"type:varchar(256);" `
}

func main(a) {
	r := gin.Default()
	db, err := gorm.Open("mysql"."Root: 123456 @ (127.0.0.1:33069)/test? charset=utf8&parseTime=True&loc=Local")
	iferr ! =nil {
		panic("Database connection failed")
	}

	db.AutoMigrate(&User{})
	defer db.Close()

	r.GET("/ping".func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "Earthy excavator",})})/ / to add
	r.GET("/add".func(c *gin.Context) {
		for i := 0; i < 10; i++ {
			user := &User{Name: "robot_" + strconv.Itoa(i), Age: i, Mail: "qwe_" + strconv.Itoa(i) + "@qq.com"} // Note the variable type
			db.Create(&user)  // Insert data in pointer object mode, id is autoincrement primary key, do not set value
		}
		c.JSON(200, gin.H{
			"message": "Add 10 data completed",})})/ / delete
	r.GET("/del".func(c *gin.Context) {
		id, _ := strconv.Atoi(c.Query("id"))  // accept url parameter id, integer,
		delUser := &User{
			ID: id,     // where id = id
		}
		db.Delete(delUser)
		c.JSON(200, gin.H{
			"message": "Deletion completed",})})/ / change
	r.GET("/update".func(c *gin.Context) {
		id, _ := strconv.Atoi(c.Query("id"))
		name := c.Query("name")
		test := &User{
			ID: id,
		}
		db.Model(&test).Update("name", name)
		c.JSON(200, gin.H{
			"message": "Update successful",})})/ / check
	r.GET("/find".func(c *gin.Context) {
		var Result User
		name := c.Query("name")  // Accept the URL parameter name
		db.Debug().Where("name = ?", name).Find(&Result)  // If you add Debug() to db, the console will print native mysql.
		c.JSON(200, gin.H{
			"message": Result,
		})
	})

	r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

Copy the code