How to use ORM in Golang

PHPz
Release: 2023-04-11 09:39:43
Original
789 people have browsed it

Golang is a compiled language that has been favored by more and more developers because of its good performance. With the development of Golang, more and more application scenarios are covered, including web development, system tools, databases, etc. Among them, database operations have also become an integral part of the daily work of Golang developers. In database operations, using the ORM framework can greatly save time and improve development efficiency. So how to use the ORM framework to operate the database in Golang? Let’s find out.

ORM (Object Relational Mapping) refers to converting data in a relational database into a set of object-oriented data by using a metadata that describes objects and relationships, and encapsulating database operations in an abstraction layer , so that we do not need to care about the underlying SQL operations during the programming process, thus simplifying the complexity of database operations and program implementation.

Currently, the more popular ORM frameworks in Golang include: GORM, XORM, QBS, etc. In this article, we will take GORM as an example to introduce in detail how to use the ORM framework in Golang.

1. Install GORM

Before you start using GORM, you need to install its corresponding dependency packages. The following are the dependency packages that need to be installed to use GORM:

go get -u github.com/jinzhu/gorm
go get -u github.com/jinzhu/gorm/dialects/mysql
Copy after login

Among them, the second dependency package is used to connect to the MySQL database.

2. Connect to the database

Before using GORM to operate the MySQL database, we need to establish a connection first. In GORM, you can connect to the MySQL database through the following code:

import (
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
)

func main() {
    //连接MySQL数据库
    db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local")
    if err != nil {
        panic("failed to connect database")
    }
    defer db.Close()
}
Copy after login

In the above code, we connect to the MySQL database through the Open() function, which contains the MySQL user name, password, database name and other information. It should be noted that adding "&charset=utf8&parseTime=True&loc=Local" at the end of the parameter can ensure that UTF-8 encoding is used and time type parsing is supported.

3. Define the structure

When using the ORM framework, you need to define the structure of the database table for mapping with the tables in the database. The following is an example of a structure that defines a user table (user):

type User struct {
    gorm.Model
    Name string // 用户名
    Age  int    // 年龄
}
Copy after login

Through the above code, several fields of the user table are mapped to attributes of the structure. Among them, "gorm.Model" is a structure provided by GORM that implements the four fields of ID, CreatedAt, UpdatedAt, and DeletedAt. These four common fields can be easily added to each table.

4. Create a data table

After defining the table structure, you also need to create the corresponding data table. In GORM, you can use the AutoMigrate() function to automatically create a data table. The following is a sample code:

func main() {
    //连接MySQL数据库
    db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local")
    if err != nil {
        panic("failed to connect database")
    }
    defer db.Close()

    //自动创建数据表
    db.AutoMigrate(&User{})
}
Copy after login

In the above code, we use the AutoMigrate() function to automatically create the user table. This function will automatically identify whether the table exists. If it does not exist, it will create a new table. If it exists, it will be omitted. Pass.

5. Operation data

After completing the above work, we can start to operate the data. In GORM, many API functions are provided to implement various CRUD (Create, Read, Update, Delete) operations. The following is sample code for some common operations:

  1. New data
//新建一条用户数据
func CreateUser(u User) error {
    return db.Create(&u).Error
}
Copy after login

In the above code, we use the Create() function to implement the operation of creating new user data.

  1. Query data
//查询指定ID的用户数据
func GetUserById(id uint) (User, error) {
    var user User
    return user, db.Where("id = ?", id).First(&user).Error
}
Copy after login

In the above code, we use the Where() and First() functions to obtain the user data of the specified ID.

  1. Update data
//更新指定ID的用户数据
func UpdateUser(id uint, name string, age int) error {
    result := db.Model(&User{}).Where("id = ?", id).Update(map[string]interface{}{"name": name, "age": age})
    if result.Error != nil {
        return result.Error
    }

    if result.RowsAffected == 0 {
        return errors.New("未找到符合条件的记录")
    }

    return nil
}
Copy after login

In the above code, we use the Model(), Where() and Update() functions to update the user data of the specified ID.

  1. Delete data
//删除指定ID的用户数据
func DeleteUser(id uint) error {
    result := db.Delete(&User{}, id)
    if result.Error != nil {
        return result.Error
    }

    if result.RowsAffected == 0 {
        return errors.New("未找到符合条件的记录")
    }

    return nil
}
Copy after login

In the above code, we use the Delete() function to delete the user data of the specified ID.

6. Summary

Using the ORM framework can greatly simplify the complexity of database operations and program implementation, save development time, and improve development efficiency. In Golang, using the GORM framework can help us operate the MySQL database more conveniently. Of course, GORM also provides many advanced operations, which will not be described here. Hope this article is helpful to you.

The above is the detailed content of How to use ORM in Golang. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template