Introduction
GORM (full name Go Object Relational Mapping) is a lightweight object relational mapping (ORM) library used in the Go language. ORM is a programming technique used to map object models to relational databases, allowing developers to use an object-oriented approach to database operations.
GORM provides a simple and powerful API, allowing developers to add, delete, modify and check databases in a simple way without directly writing SQL statements. It supports a variety of databases, including MySQL, PostgreSQL, SQLite, etc., and provides rich functions, such as transaction processing, association relationship, preloading, model verification, etc.
Using GORM, you can define Go structs to represent tables in the database. GORM will automatically create, modify and query databases based on these struct definitions. It provides a wealth of methods and options, which can conveniently perform conditional query, pagination, sorting and other operations.
Install GORM
To install GORM, run the following command:
go get -u /gorm go get -u /driver/mysql
This will install the GORM core library as well as the MySQL driver.
Connect to the database
First, we need to connect to the database. Here is an example of using GORM to connect to a MySQL database:
package main import ( "/driver/mysql" "/gorm" ) func main() { dsn := "user:password@tcp(localhost:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local" db, err := ((dsn), &{}) if err != nil { panic("failed to connect database") } // ... }
In this example, we use the () function to connect to the database. The () function accepts a DSN string containing database connection information.
Define the model
GORM uses structures to represent tables in a database. In this example, we will create a structure called User to represent a user table:
type User struct { ID uint Name string Age int }
GORM uses a convention when processing database table names: it converts the structure name to a plural form and uses it as the database table name. This is the default behavior of GORM. So, when you define a struct called User, GORM automatically maps it to a table named users.
This convention originated from a convention in many programming languages and frameworks, which means that table names are represented as plural forms to indicate that tables contain multiple records.
If you want to customize the table name, you can implement the Tabler interface of GORM in the structure. Here is an example:
type User struct { ID uint Name string Age int } func (u User) TableName() string { return "custom_users" }
In this example, we implemented the TableName() method and returned the custom table name "custom_users". GORM will now use "custom_users" as the table name, instead of the default "users".
GORM will automatically map the structure name to the corresponding table name. In this case, it will look for a table named users . You can also use the GORM tag to customize field and table names.
type User struct { ID uint `gorm:"column:id;primary_key"` // Custom field name is "id" and set as primary key Name string `gorm:"column:name;type:varchar(100)"` // Custom field name is "name" and set to VARCHAR type, maximum length is 100 Age int `gorm:"column:age;type:int;not null"` // The custom field is named "age" and is set to INT type, and is not allowed to be NULL} // Use TableName method to customize the table namefunc (User) TableName() string { return "custom_users" }
Automatic migration
GORM supports automatic migration, which means it can automatically create and update database table structures. To perform an automatic migration, call the AutoMigrate() function:
(&User{})
Note that the AutoMigrate() function does not delete data in the table or delete unused columns.
Basic CRUD operation
Insert record
To insert a new record, you can use the Create() function:
user := User{Name: "John Doe", Age: 25} result := (&user)
The Create() function inserts a new record into the database and updates the primary key field in the structure.
Query records
To query records, you can use various query methods provided by GORM, such as First(), Find(), and Where():
// Query a single recordvar user User result := (&user, 1) // Use primary key to queryresult := ("name = ?", "John Doe").First(&user) // Use condition query // Query multiple recordsvar users []User result := (&users) // Query all user recordsresult := ("age > ?", 25).Find(&users) // Query multiple records using conditions
GORM supports chain queries, and you can combine multiple query conditions as needed.
Update records
To update a record, you can use the Save() or Updates() function:
// Update a single recorduser := User{ID: 1, Name: "Jane Doe", Age: 30} result := (&user) //Update records with primary key //Update multiple records using conditionsresult := (&User{}).Where("age > ?", 25).Updates(User{Name: "Updated Name"})
The Save() function updates the record with the primary key, while the Updates() function can update one or more records, depending on the conditions provided.
Delete records
To delete a record, you can use the Delete() function:
// Delete a single recorduser := User{ID: 1} result := (&user) // Use the primary key to delete the record // Use conditions to delete multiple recordsresult := ("age < ?", 18).Delete(&User{})
The Delete() function can delete one or more records, depending on the conditions provided.
Detailed API explanation
1. Query
Query a single record
var user User // Get the first record of the matching condition(&user, 1) // Query according to the primary key("name = ?", "John Doe").First(&user) // Query according to the conditions // Get any record of matching conditions(&user) ("name = ?", "John Doe").Take(&user) // Get the last record of the matching condition(&user) ("name = ?", "John Doe").Last(&user)
Query multiple records
var users []User // Get all records of matching conditions(&users) ("age > ?", 25).Find(&users)
Conditional query
var users []User // Add a condition for the query("name = ?", "John Doe").Find(&users) // Add or condition for query("name = ?", "John Doe").Or("name = ?", "Jane Doe").Find(&users) // Add non-conditions to the query("name = ?", "John Doe").Find(&users)
Sort, limit, and offset
var users []User // Sort the query results("age desc").Find(&users) // Limit the number of query results(5).Find(&users) // Set the offset of query results(10).Find(&users)
2. Insert
user := User{Name: "John Doe", Age: 25} result := (&user)
3. Update
// Update a single recorduser := User{ID: 1, Name: "Jane Doe", Age: 30} result := (&user) //Update records with primary key //Update multiple records using conditionsresult := (&User{}).Where("age > ?", 25).Updates(User{Name: "Updated Name"})
4. Delete
// Delete a single recorduser := User{ID: 1} result := (&user) // Use the primary key to delete the record // Use conditions to delete multiple recordsresult := ("age < ?", 18).Delete(&User{})
Summarize
GORM (Go Object Relational Mapping) is a lightweight object-relational mapping (ORM) library used to perform database operations in the Go language. Here is a summary of GORM:
- Ease of use: GORM provides a simple and powerful API that allows developers to use an object-oriented approach to database operations without having to write SQL statements directly. It uses an intuitive syntax that is easy to understand and use.
- Database support: GORM supports a variety of databases, including MySQL, PostgreSQL, SQLite, etc., which can easily switch different database engines without changing code.
- Automatic mapping: By defining a structure in the Go language to represent tables in the database, GORM can automatically create, modify and query databases. It uses a convention-better configuration method to map structure fields to the columns of database tables, simplifying the process of database operations.
- Query and Conditions: GORM provides a wealth of methods and options, which can conveniently perform conditional query, pagination, sorting and other operations. It supports chain calls, making query code clearer and easier to combine.
- Associative relationship: GORM supports defining and processing relationships between tables, including one-to-one, one-to-many, many-to-many and other relationships. It provides a way to automatically handle the loading, saving and deletion of associations, simplifying complex database association operations.
- Transaction processing: GORM supports transaction operations, which can ensure the atomicity of a series of database operations. By using transactions, data consistency and integrity can be ensured while improving database performance and efficiency.
- Preload and lazy loading: GORM supports preloading associated data, reducing the number of queries in the database and improving performance. At the same time, it also supports lazy loading, only loading associated data when needed, avoiding unnecessary data loading.
- Model Verification: GORM provides model verification function, which can verify fields in structures to ensure the legality and integrity of the data. It supports custom verification rules and provides convenient verification methods, simplifying the process of data verification.
In short, GORM is a feature-rich and easy-to-use ORM library that simplifies the process of interacting with databases in Go. By using GORM, developers can operate databases more easily, reducing the workload of writing SQL statements, and improving development efficiency and maintainability of code.
The above is the detailed content of the guide to using GORM in Go language. For more information about GORM in Go language, please pay attention to my other related articles!