This article was first published in personal wechat public number code curious station welcome attention
With the expansion of the project, one day, in the table and table field in the project of countless more, if still using SQL language to perform add and delete, be sure to bring a lot of tedious things, for example we want to add a field more than a dozen of structure, the structure of each attribute to write it again. Greatly reduces the development speed, but also introduces some errors, so we need to introduce some framework to manage the database, convenient for us to complete the project. Here we introduce GORM
🥨 gorm
Gorm is one of the better known ORM frameworks in Go, with 14.6 K stars on Github. Gorm has implemented most of the common functions. Adding GORM to GIN is very simple.
Start by opening our initDB folder. Change SQL.Open to gorm.Open at the same time introduce GORm, at the same time change Db definition type, *gorm. The specific code is as follows:
package initDB
import(_"github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"log"
)
var Db *gorm.DB
func init(a) {
var err error
Db, err = gorm.Open("mysql"."Root: 1234 @ TCP (127.0.0.1:3306)/ginhello")
iferr ! =nil {
log.Panicln("err:", err.Error())
}
}
Copy the code
At this point our introduction of the framework is complete.
Because we have modified Db attributes, there is an error in article. Go at this time.
So we modify it, using THE GORM API.
🍗 to add, delete, change, and check
increase
Add method, before using SQL language to achieve add, as follows:
result, e := initDB.Db.Exec("insert into ` article` (type, content) values (? ,?) ;", article.Type, article.Content)
Copy the code
Now we will implement this process through the framework.
create := initDB.Db.Create(&article)
Copy the code
Isn’t that easy?
Query a single
Pass the restriction through article.Id, which is only used if the primary key is int.
initDB.Db.First(&article, article.Id)
return article
Copy the code
Query all
var articles []Article
initDB.Db.Find(&articles)
return articles
Copy the code
delete
initDB.Db.Delete(article)
Copy the code
Through some of the above methods can be seen, the basic before the increase, deletion, change to check the code has greatly shortened, greatly reduce the occurrence of errors.
At this point, we can run our code, either through.http or through unit tests, but it will return an error. Error as follows:
Error 1146: Table 'ginhello.articles' doesn't exist
Copy the code
The articles table does not exist in the GinHello library. We don’t write articles, we write articles.
Originally gorM in the corresponding structure of the default will add an S, so we now have two methods, the first is to change the declaration, but the declaration is often can not be arbitrarily modified. The second is to change the code so that we are looking for articles instead of articles.
func (article Article) TableName(a) string {
return "article"
}
Copy the code
Implement this interface, which returns a string that defines the table we need to associate with.
At this point, we run our code again and find that the function can be used completely, and no errors are reported.
🚥 Automatic table creation
Join a new project and no database tables have been created, or move the project to another environment and there are no database tables on the environment.
Gorm gives us the ability to create database tables.
Let’s create a new model called comment to manage comments.
package model
type Comment struct {
ID int
content string
}
Copy the code
I want to capitalize all the ids here.
After the structure is established, the corresponding database table can be established on the structure.
For creating a table we first check whether the table exists, if there is no need to rebuild, do not run the project to the previous data overwrite.
func init(a) {
table := initDB.Db.HasTable(Comment{})
if! table { initDB.Db.CreateTable(Comment{}) } }Copy the code
Running our project, we will find that the database has created a new table. If we want to index the id at the same time, we can specify the structure tag. The following
type Comment struct {
ID int `gorm:"index:idx_id"`
Content string
}
Copy the code
Delete the table you just created and rerun the code. The IDx_ID index will be added to the database table.
⚓ Use of gorM Model
When we set up the database, we will set up the primary key ID for each table. If you have read the Alibaba Java development specification, you should also know some other necessary information, such as creation time, modification time, etc.
This is where the Gorm Model comes in, and it has encapsulated the properties for us.
We need to change the structure to look like this
type Comment struct {
gorm.Model
Content string
}
Copy the code
Delete the previous table structure, rerun the project, and a new table structure will be generated.
✍ summary
Through the brief learning in this chapter, WE can basically integrate GORM into our GIN project and operate the database, which greatly reduces our code volume. If there is time, there may be a special introduction to gorM later.
👨💻 Code of this section
Github
Related to recommend
Gin(I):Hello Gin(II): Routing Router Gin(III): Template TMPL Gin(IV): Form submission checksum model binding Gin(V): Connection to MySQL Gin(VI): File upload Gin(VII): Use and definition of middleware Gin(eight): use of cookies Gin(nine): generate restful interfaces Gin(ten): integrate Swagger