What is Object Relational Mapping ORM? What are the pros and cons? Implementation of ORM in go language - gorm

ORM

Professionally speaking, it is the mapping between the object model and the relational database.
My understanding is that ORM provides API for us to operate the database.

advantage:

ORM tools usually provide a set of API and query language, so that developers can use object-oriented approach to database operations without knowing the details of the underlying database. ORM tools can automatically generate SQL statements.

  • Improve code readability and maintainability;
  • Simplified interaction with the database ;
  • Improved development efficiency ;
  • It can reduce the possibility of security issues such as SQL injection . (Also parameterized and filtered input can also prevent SQL injection)

shortcoming:

  • Performance issues: ORM tools may introduce additional overhead, resulting in performance degradation;
  • Limitations: ORM tools may not be suitable for all database operations.

gorm - ORM framework for Go language

The structure in the Go language can be mapped to the table in the relational database, thus simplifying the interaction with the database

type User struct {
    
    
    ID        uint   `gorm:"primary_key"`
    Name      string `gorm:"type:varchar(100);unique_index"`
    Email     string `gorm:"type:varchar(100);unique_index"`
    Password  string `gorm:"type:varchar(100)"`
    CreatedAt time.Time
    UpdatedAt time.Time
}
// 创建新用户
user := User{
    
    Name: "Tom", Email: "[email protected]", Password: "123456"}
db.Create(&user)

// 查询用户
var users []User
db.Find(&users)
for _, user := range users {
    
    
    fmt.Println(user.Name, user.Email)
}

// 更新用户信息
var user User
db.First(&user, 1)
user.Name = "Jerry"
db.Save(&user)

// 删除用户
var user User
db.First(&user, 1)
db.Delete(&user)

In the above code, we used some APIs in GORM, such as Create(), Find(), First(), Save() and Delete(), etc. These APIs can help us perform database operations without writing SQL statements directly.

Guess you like

Origin blog.csdn.net/csxylrf/article/details/130457463