Master Go’s XORM: From Installation to Advanced CRUD Operations
This tutorial walks through installing the Go XORM library, generating Go structs from existing MySQL tables with the reverse tool, and demonstrates full CRUD, pagination, and transaction handling using both chainable queries and raw SQL.
xorm
Officially described as a simple yet powerful Go ORM library, xorm makes database operations straightforward while still encouraging developers to understand SQL; it supports mixing two styles of usage.
xorm also provides a reverse command that generates Go structs from existing database tables, saving manual coding effort. Official site: https://xorm.io/
Installation
Visit the xorm GitHub repository (https://github.com/go-xorm) and download two packages: the core xorm package and the cmd tool package for the reverse command.
Run the following commands:
go get github.com/go-xorm/xorm go get github.com/go-xorm/cmd/xormAfter downloading, the github.com folder will contain the go-xorm packages.
Generating Data Structure structs
Assume a local MySQL database test with two tables doctor_tb and user_tb.
Steps:
1. Create a folder xorm_models in any project to store generated code.
2. Copy the template directory from the cmd tool ( github.com/go-xorm/cmd/xorm/templates/goxorm) into xorm_models.
3. Open a command line, navigate to xorm_models, and run:
xorm reverse mysql root:112233@tcp(127.0.0.1:3305)/test?charset=utf8 templates/goxorm4. The generated struct files appear under xorm_models/models, e.g., doctor_tb.go and user_tb.go.
package models
import (
"time"
)
type DoctorTb struct {
Id int `xorm:"not null pk autoincr INT(11)"`
Name string `xorm:"default '' comment('姓名') VARCHAR(50)"`
Age int `xorm:"default 0 comment('年龄') INT(11)"`
Sex int `xorm:"default 0 comment('性别') INT(11)"`
Addtime time.Time `xorm:"DATETIME"`
}Using xorm
xorm supports chainable queries such as:
engine.Where("age > ?", 40).Or("name like ?", "林%").OrderBy("Id desc").Find(&docList2)It also allows direct SQL execution:
engine.SQL("select * from doctor_tb where age > ?", 40).Find(&docList4)The following demo covers common operations: single record query, list query, pagination, insertion, update, deletion, and transaction handling.
package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/go-xorm/xorm"
"goShare/xorm_models/models"
"time"
)
func main() {
engine, err := xorm.NewEngine("mysql", "root:112233@tcp(127.0.0.1:3305)/test?charset=utf8")
if err != nil { fmt.Println(err); return }
if err := engine.Ping(); err != nil { fmt.Println(err); return }
defer engine.Close()
fmt.Println("Database connection successful")
// Query single record
var doc models.DoctorTb
found, _ := engine.Where("name = ?", "钟南山").Get(&doc)
if found { fmt.Println(doc) } else { fmt.Println("Data not found") }
// Insert new record
doc3 := models.DoctorTb{0, "王医生", 48, 1, time.Now()}
if i, _ := engine.InsertOne(doc3); i > 0 { fmt.Println("Insert result:", i) }
// Query list with pagination
var list []models.DoctorTb
page, pageSize := 0, 2
total, _ := engine.Where("age > ? or name like ?", 40, "林%").Limit(pageSize, page*pageSize).FindAndCount(&list)
fmt.Println("Total:", total, "List:", list)
// Transaction example
sess := engine.NewSession()
defer sess.Close()
if err := sess.Begin(); err != nil { fmt.Println(err); return }
if _, err := sess.Exec("delete from doctor_tb where Id = ?", 6); err != nil { sess.Rollback(); fmt.Println(err); return }
if _, err := sess.Exec("delete from user_tb where Id = ?", 10); err != nil { sess.Rollback(); fmt.Println(err); return }
if err := sess.Commit(); err != nil { fmt.Println(err); return }
fmt.Println("Transaction succeeded")
}Summary
Key steps: 1) Download the xorm core and cmd packages; 2) Copy the template directory to a generation folder; 3) Use xorm reverse to auto‑generate struct code; 4) Create an engine with xorm.NewEngine(); 5) Perform CRUD, pagination, and transactions with concise, chainable calls.
The demo provides common business‑level operations; if you found it useful, consider giving it a like.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
