乐闻世界logo
搜索文章和话题

What is GORM and what are its core features?

3月6日 23:39

GORM (Go Object-Relational Mapping) is one of the most popular ORM libraries in the Go language, providing powerful database operation capabilities.

Core Features

  1. Full-featured ORM: Supports associations, hooks, preloading, transactions, and more
  2. Associations: Supports Has One, Has Many, Many To Many, Belongs To relationships
  3. Hooks: Supports Before/After Create, Save, Update, Delete, Find hooks
  4. Auto Migration: Supports automatic table creation, foreign keys, indexes, etc.
  5. Chainable API: Provides fluent API design with chainable operations
  6. 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 record
  • Find(): Query multiple records
  • Where(): Add query conditions
  • Create(): Create record
  • Update(): Update record
  • Delete(): Delete record
  • Preload(): Preload associated data
  • Joins(): Execute JOIN queries

GORM follows the convention over configuration design philosophy, allowing developers to quickly perform database operations while maintaining code simplicity and maintainability.

标签:Gorm