GORM (Go Object-Relational Mapping) is one of the most popular ORM libraries in the Go language, providing powerful database operation capabilities.
Core Features
- Full-featured ORM: Supports associations, hooks, preloading, transactions, and more
- Associations: Supports Has One, Has Many, Many To Many, Belongs To relationships
- Hooks: Supports Before/After Create, Save, Update, Delete, Find hooks
- Auto Migration: Supports automatic table creation, foreign keys, indexes, etc.
- Chainable API: Provides fluent API design with chainable operations
- Multi-database Support: MySQL, PostgreSQL, SQLite, SQL Server, etc.
Basic Usage Example
go// Define model type User struct { gorm.Model Name string Email string `gorm:"type:varchar(100);uniqueIndex"` Age int } // Connect to database db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) // Create record db.Create(&User{Name: "John", Email: "john@example.com", Age: 30}) // Query record var user User db.First(&user, 1) // Query record with primary key 1 // Update record db.Model(&user).Update("Age", 31) // Delete record db.Delete(&user)
Common Methods
First(): Query first recordFind(): Query multiple recordsWhere(): Add query conditionsCreate(): Create recordUpdate(): Update recordDelete(): Delete recordPreload(): Preload associated dataJoins(): Execute JOIN queries
GORM follows the convention over configuration design philosophy, allowing developers to quickly perform database operations while maintaining code simplicity and maintainability.