codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🐹

Go (Golang)

43 / 72 topics
42Third-Party Libraries Overview43GORM (Object-Relational Mapping)44Gin Framework45Echo Framework46Cobra CLI Library47Viper Config Library48Go Bindata for Embedding Assets49gRPC (Remote Procedure Calls)50Protocol Buffers
Tutorials/Go (Golang)/GORM (Object-Relational Mapping)
🐹Go (Golang)

GORM (Object-Relational Mapping)

Updated 2026-04-20
2 min read

GORM (Object-Relational Mapping)

Introduction

GORM is a powerful ORM library for the Go programming language. It simplifies database interactions by allowing developers to work with data using structs and methods instead of writing raw SQL queries. This guide will walk you through setting up GORM, defining models, performing CRUD operations, and integrating it into your Go applications.

Prerequisites

Before diving into GORM, ensure you have the following:

  • Basic knowledge of Go programming.
  • A working Go environment (Go 1.16 or later).
  • Familiarity with SQL databases like MySQL, PostgreSQL, SQLite, etc.

Installation

To install GORM, use the following command:

go get -u gorm.io/gorm

For database drivers, you need to install them separately. For example, for MySQL:

go get -u gorm.io/driver/mysql

Setting Up a Basic Connection

To connect to a database using GORM, you first need to import the necessary packages and establish a connection.

package main

import (
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "log"
)

func main() {
    // Define your database connection string
    dsn := "user:password@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"

    // Open a connection to the database
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    if err != nil {
        log.Fatalf("failed to connect database: %v", err)
    }

    // Ping the database to ensure the connection is alive
    sqlDB, _ := db.DB()
    defer sqlDB.Close()

    if err := sqlDB.Ping(); err != nil {
        log.Fatalf("failed to ping database: %v", err)
    }

    log.Println("Successfully connected to the database!")
}

Defining Models

In GORM, models are defined as structs. Each struct field corresponds to a column in the database table.

type User struct {
    gorm.Model // Includes ID, CreatedAt, UpdatedAt, DeletedAt fields
    Name       string
    Email      string `gorm:"unique"`
}

The gorm.Model struct includes common fields like ID, CreatedAt, UpdatedAt, and DeletedAt, which are automatically managed by GORM.

Migrations

GORM provides a simple way to perform database migrations using the AutoMigrate method.

func main() {
    // ... (previous code)

    // Auto-migrate the schema
    db.AutoMigrate(&User{})

    log.Println("Database migration completed!")
}

The AutoMigrate method will create tables, add missing columns, and change column types if necessary. Note that it won't delete or modify existing data.

CRUD Operations

Creating Records

To insert a new record into the database, use the Create method.

func main() {
    // ... (previous code)

    user := User{Name: "John Doe", Email: "john@example.com"}
    result := db.Create(&user)
    if result.Error != nil {
        log.Fatalf("failed to create record: %v", result.Error)
    }

    log.Printf("User created with ID: %d\n", user.ID)
}

Reading Records

To query records, use the First, Last, or Find methods.

func main() {
    // ... (previous code)

    var user User
    if err := db.First(&user).Error; err != nil {
        log.Fatalf("failed to find record: %v", err)
    }

    log.Printf("Found user: %+v\n", user)
}

Updating Records

To update a record, use the Save or Updates methods.

func main() {
    // ... (previous code)

    var user User
    if err := db.First(&user).Error; err != nil {
        log.Fatalf("failed to find record: %v", err)
    }

    user.Name = "Jane Doe"
    result := db.Save(&user)
    if result.Error != nil {
        log.Fatalf("failed to update record: %v", result.Error)
    }

    log.Printf("User updated with ID: %d\n", user.ID)
}

Deleting Records

To delete a record, use the Delete method.

func main() {
    // ... (previous code)

    var user User
    if err := db.First(&user).Error; err != nil {
        log.Fatalf("failed to find record: %v", err)
    }

    result := db.Delete(&user)
    if result.Error != nil {
        log.Fatalf("failed to delete record: %v", result.Error)
    }

    log.Printf("User deleted with ID: %d\n", user.ID)
}

Advanced Features

Associations

GORM supports various associations like BelongsTo, HasOne, HasMany, and ManyToMany.

type Profile struct {
    gorm.Model
    UserID uint
    User   User
    Bio    string
}

func main() {
    // ... (previous code)

    db.AutoMigrate(&User{}, &Profile{})

    user := User{Name: "John Doe", Email: "john@example.com"}
    profile := Profile{Bio: "Software Developer"}

    db.Create(&user).Association("Profiles").Append(&profile)
}

Preloading

To eagerly load associations, use the Preload method.

func main() {
    // ... (previous code)

    var user User
    if err := db.Preload("Profile").First(&user).Error; err != nil {
        log.Fatalf("failed to find record: %v", err)
    }

    log.Printf("User with profile: %+v\n", user)
}

Transactions

To perform database transactions, use the Begin method.

func main() {
    // ... (previous code)

    tx := db.Begin()
    if tx.Error != nil {
        log.Fatalf("failed to start transaction: %v", tx.Error)
    }

    user := User{Name: "John Doe", Email: "john@example.com"}
    if err := tx.Create(&user).Error; err != nil {
        tx.Rollback()
        log.Fatalf("failed to create record in transaction: %v", err)
    }

    tx.Commit()
    log.Printf("User created with ID: %d\n", user.ID)
}

Best Practices

  1. Use Struct Tags: Use struct tags to define column names, constraints, and other properties.
  2. Error Handling: Always check for errors after database operations.
  3. Migrations: Use migrations to manage schema changes instead of manually altering tables.
  4. Transactions: Use transactions for complex operations that require atomicity.

Conclusion

GORM is a powerful ORM library for Go that simplifies database interactions and reduces the amount of boilerplate code you need to write. By following this guide, you should have a solid understanding of how to set up GORM, define models, perform CRUD operations, and integrate it into your Go applications.


PreviousThird-Party Libraries OverviewNext Gin Framework

Recommended Gear

Third-Party Libraries OverviewGin Framework