GORM for Go: Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is GORM and why is it needed?



GORM is a powerful and popular ORM (Object-Relational Mapping) library for the Go language. It provides developers with a convenient way to interact with relational databases (PostgreSQL, MySQL, SQLite, SQL Server, etc.) using an object-oriented approach in Go.



Why is GORM needed?

  • CRUD Automation: GORM handles writing boilerplate SQL code for creating, reading, updating, and deleting records.
  • Schema Migrations: Allows automatic creation and updating of database tables based on your Go structs.
  • Table Relationships: Simplifies working with one-to-many, many-to-many, and one-to-one relationships.
  • Security: Built-in protection against SQL injection through parameterized queries.
  • Performance: Supports Lazy Loading, Eager Loading, and caching.
  • Community: Large community, many plugins and extensions.


Installing GORM



GORM is installed using the standard method for Go packages. Make sure you have Go installed (version 1.18+).



go get -u gorm.io/gormgo get -u gorm.io/driver/sqlite  # For SQLitego get -u gorm.io/driver/mysql   # For MySQLgo get -u gorm.io/driver/postgres # For PostgreSQLgo get -u gorm.io/driver/sqlserver # For SQL Server


Note: Unlike Python (pip) or Node.js (npm), Go does not have a single package manager. The go get command downloads the source code and compiles it into your project.



Quick Start with Code Example



Let's create a simple application for managing users using SQLite.



package main

import ( "fmt" "gorm.io/driver/sqlite" "gorm.io/gorm")

// User — data model corresponding to a table in the DBtype User struct { ID uint `gorm:"primaryKey"` Name string `gorm:"size:100;not null"` Email string `gorm:"uniqueIndex;size:255"` Age int}

func main() { // 1. Database connection db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { panic("failed to connect database") }

// 2. Auto-migration — creating the table db.AutoMigrate(&User{})

// 3. Creating a record (Create) user := User{Name: "Ivan Petrov", Email: "ivan@example.com", Age: 30} result := db.Create(&user) if result.Error != nil { fmt.Println("Error creating:", result.Error) } fmt.Printf("User created with ID: %d", user.ID)

// 4. Reading a record (Read) var readUser User db.First(&readUser, user.ID) // Search by primary key fmt.Printf("User found: %+v", readUser)

// 5. Updating a record (Update) db.Model(&readUser).Update("Age", 31) fmt.Printf("Updated age: %d", readUser.Age)

// 6. Deleting a record (Delete) db.Delete(&readUser) fmt.Println("User deleted")}


Main GORM Methods/Functions



1. gorm.Open(dialector, config)

What it does: Establishes a connection to the database. Returns a *gorm.DB instance.

Parameters:

  • dialector — database driver (e.g., sqlite.Open, mysql.Open, postgres.Open).
  • config — GORM configuration (gorm.Config).

Example:

db, err := gorm.Open(mysql.Open("user:password@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"), &gorm.Config{})


2. db.AutoMigrate(models ...interface{})

What it does: Automatically creates or updates ta

Recommendations