GORM là gì?
GORM (Go Object Relational Mapper) là một thư viện ORM cho Go giúp lập trình viên dễ dàng làm việc với cơ sở dữ liệu thông qua các struct thay vì viết câu lệnh SQL thủ công.
GORM hỗ trợ nhiều CSDL như:
- PostgreSQL
- MySQL
- SQLite
- SQL Server
Các tính năng chính
- Tự động migrate schema (tạo bảng từ struct)
- Hỗ trợ CRUD đầy đủ
- Hỗ trợ các loại quan hệ: One-To-One, One-To-Many, Many-To-Many
- Hỗ trợ transaction
- Truy vấn với hooks, preload
- Hỗ trợ SQL thuần khi cần
- Tùy chỉnh bảng, cột, index, khóa chính/phụ, khóa ngoại, constraints,…
Cài đặt và cấu hình
Cài đặt thư viện
go get -u gorm.io/gorm go get -u gorm.io/driver/postgres # Có thể dùng mysql, sqlite, sqlserver
Kết nối đến CSDL (ví dụ PostgreSQL)
import ( "gorm.io/gorm" "gorm.io/driver/postgres" ) func ConnectDB() (*gorm.DB, error) { dsn := "host=localhost user=postgres password=yourpassword dbname=testdb port=5432 sslmode=disable" db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) return db, err }
Tạo model với GORM
Ví dụ model User:
type User struct { ID uint `gorm:"primaryKey"` Name string Email string `gorm:"uniqueIndex"` Age int CreatedAt time.Time UpdatedAt time.Time }
gorm:"primaryKey"
→ đánh dấu cột là khóa chínhgorm:"uniqueIndex"
→ tạo index duy nhất
Tự động tạo bảng từ struct:
db.AutoMigrate(&User{})
Các thao tác CURD với GORM
CREATE
user := User{Name: "Alice", Email: "[email protected]", Age: 25} result := db.Create(&user) // tạo bản ghi
READ
var user User db.First(&user, 1) // Tìm theo ID db.Where("email = ?", "[email protected]").First(&user) var users []User db.Find(&users) // Lấy tất cả
UPDATE
db.Model(&user).Update("Age", 26) db.Model(&user).Updates(User{Name: "Bob", Age: 30}) // cập nhật nhiều trường
DELETE
db.Delete(&user) db.Delete(&User{}, 1) // Xoá theo ID
Quản lý mối quan hệ trong GORM
One-to-One
type Profile struct { ID uint UserID uint Bio string } type User struct { ID uint Name string Profile Profile `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"` }
One-to-Many
type Post struct { ID uint Title string UserID uint } type User struct { ID uint Name string Posts []Post }
Many-to-Many
type User struct { ID uint Name string Roles []Role `gorm:"many2many:user_roles"` } type Role struct { ID uint Name string }
Preload dữ liệu quan hệ
var user User db.Preload("Profile").First(&user) db.Preload("Posts").Find(&user)