Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Data Types in Go
  • Go Keywords
  • Go Control Flow
  • Go Functions
  • GoLang Structures
  • GoLang Arrays
  • GoLang Strings
  • GoLang Pointers
  • GoLang Interface
  • GoLang Concurrency
Open In App
Next Article:
Setting Up Gorm With MySQL
Next article icon

Setting Up Gorm With MySQL

Last Updated : 04 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we’ll set up GORM, an ORM library, with MySQL using the Gin web framework in Go. GORM provides features that make database interactions easier by allowing the use of Go structs instead of raw SQL queries, which helps reduce boilerplate code and keeps the codebase cleaner.

We’ll take a step-by-step approach to establishing a database connection, implementing basic CRUD operations, and managing database migrations. Additionally, we’ll perform a simple query using the Gin API and GORM while maintaining a clear and simple folder structure for easier understanding.

What Is Go ?

Go is a simple and efficient programming language designed for fast performance and concurrency, making it ideal for robust applications. Developed by Google, it emphasizes clean syntax and ease of use, which speeds up development and improves maintainability.

What is Gin ?

Gin is a web framework built on Go's net/http package, offering high speed. Combined with Go's concurrency, it is widely used in efficient cloud-based applications. Understanding Gin's interaction with databases like MySQL is crucial for building web applications efficiently.

Features Provided By Gorm

  • Makes tasks handling easier, such as: CRUD (Create, Read, Update, Delete) operations, associations, transactions, and migrations.
  • GORM manages database connection pooling by default which is a more optimized and scalable approach than a single connection.
  • Share similar functional and database interaction logic to other ORM libraries like Sequelize (for Node.js) or Prisma.

Step-by-Step Guide to Setting Up GORM with MySQL in Gin

1. Setting Up the Gin Module

Initialize Gin using the following command:

go mod init MODULE_NAME
go get -u github.com/gin-gonic/gin

2. Installing GORM and MySQL driver package

Install GORM and MySQL driver package using the following command:

go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql

3. Structuring the Project

  • We will keep the folder structure simple.
  • Database directory to hold the database configurations and table structures
    .
  • We will define a struct named Countries, which will correspond to the countries table in our MySQL database.

mainDirectory

│ go.mod

│ go.sum

│ main.go

│

└───database

│ dbConfig.go

│

└───models

countries.go

4. Setting Up main.go

  • Initialize the database by calling the Init function, which is imported from the database package within the project.
  • Initialize the Gin router using the gin.Default() function and define endpoints to handle API requests.
  • Perform database interactions according to the project's requirements. In this case, we will execute two simple operations using GORM: first, adding a row to the countries table, and second, fetching all records from the countries table.
  • In the /add-country API, we will convert the incoming payload into a struct using BindJSON, then use the Create function to insert the entry into the database table, returning the inserted row as the response.
  • In the /get-all-countries API, we will declare an allCountries array to hold models. Countries structs will be used to store all the query results.
  • Make sure to explicitly check for potential errors and send appropriate status responses to enhance the application's readability and maintainability.
  • Run the router using the router.Run() command, which listens on port 8080 by default.

Example structure for main.go:

package main
import (
"net/http"
"github.com/gin-gonic/gin"
"MODULE_NAME/database"
"MODULE_NAME/database/models"
)

func main(){
databaseInstance:= database.InIt()

router:=gin.Default()

router.POST("/add-country", func(c *gin.Context){ // Payload: {"Country":"India", "CountryCode":"+91"}

var newCountry models.Countries

if err := c.BindJSON(&newCountry); err != nil{
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}

if err:= databaseInstance.Create(&newCountry).Error; err!=nil{
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}

c.JSON(200, gin.H{
"success": true,
"message":"Country Added Successfully",
"newCountry":newCountry,
})
})


router.GET("/get-all-countries", func(c *gin.Context){

allCountries:= [] models.Countries{};

if err:= databaseInstance.Find(&allCountries).Error; err!=nil{
c.JSON(http.StatusInternalServerError, gin.H{"success":false, "error":err.Error()})
return
}

c.JSON(http.StatusOK, gin.H{"success":true, "allCountries": allCountries})
})

router.Run(":8080")


5. Setting Up dbConfig.go

  • We will use the os, log, and time packages to log and record any errors to the console, and the strconv package to convert string environment variables to integers, ensuring we maintain the correct data type constraints.
  • The Init() function connects to the database, creates an instance from the connection pool for database interactions, and automatically migrates the database tables based on the structs, specifically &models.Countries{}.
  • The connectionDatabase() function establishes a connection to the database and configures the connection pool settings using credentials retrieved from environment variables.
  • The performMigration() function migrates the struct and synchronizes it with the database table to address any configuration mismatches.
  • The getEnv() function retrieves environment variables and returns a default value if the specified key is not found.

Example dbConfig.go:

package database

import (
"fmt"
"os"
"log"
"time"
"strconv"

"gorm.io/gorm"
"gorm.io/driver/mysql"
"gorm.io/gorm/logger"
"MODULE_NAME/database/models"
)

var databaseInstance *gorm.DB

func InIt() *gorm.DB{

var err error
databaseInstance, err = connectionDatabase()
if err!=nil{
log.Fatalf("Could not connect to the database: %v", err)
}

err = performMigration()
if err!=nil{
log.Fatalf("Could not auto migrate: %v", err)
}

return databaseInstance

}

func connectionDatabase() (*gorm.DB, error){

dbUsername := getEnv("DB_USERNAME", "root")
dbPassword := getEnv("DB_PASSWORD", "")
dbName := getEnv("DB_NAME", "gorm")
dbHost := getEnv("DB_HOST", "localhost")
dbPort := getEnv("DB_PORT", "3306")

connectionString := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true&loc=Local", dbUsername, dbPassword, dbHost, dbPort, dbName)

databaseConnection, err := gorm.Open(mysql.Open(connectionString), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info), // Enable logging for debugging
})

if err!=nil{
return nil, err
}

sqlDatabase, err :=databaseConnection.DB()
if err!=nil{
return nil,err
}

// Connection pool settings from environment variables
maxIdleConns, _ := strconv.Atoi(getEnv("DB_MAX_IDLE_CONNS", "10"))
maxOpenConns, _ := strconv.Atoi(getEnv("DB_MAX_OPEN_CONNS", "25"))
connMaxLifetime, _ := strconv.Atoi(getEnv("DB_CONN_MAX_LIFETIME", "3600")) // in seconds

sqlDatabase.SetMaxIdleConns(maxIdleConns)
sqlDatabase.SetMaxOpenConns(maxOpenConns)
sqlDatabase.SetConnMaxLifetime(time.Duration(connMaxLifetime) * time.Second)

return databaseConnection, nil
}

func performMigration() error{
err:= databaseInstance.AutoMigrate(&models.Countries{})
if err!=nil{
return err
}
return nil
}

func getEnv(key string, defaultVaule string) string {
value:= os.Getenv(key)
if value==""{
return defaultVaule
}
return value
}

6. Setting Up countries.go

  • The countries.go file will define the schema for the corresponding countries table in the database. The Id field is a uint, which corresponds to the id field in the database, constrained as a primary key that auto-generates its value.
  • Country attribute is a string (VARCHAR) with a NOT NULL constraint, and the CountryCode is also a string that cannot be null.

Example countries.go:

package models

type Countries struct {
Id uint `json:"id" gorm:"primarykey;autoIncrement"`
Country *string `json:"country" gorm:"not null"`
CountryCode *string `json:"countryCode" gorm:"not null"`
}

7. Starting the Application

Start the application using the following command

go run main.go

Conclusion

In conclusion, while GORM may not achieve the raw speed of direct SQL queries due to the inherent overhead of its abstraction layer, it offers substantial advantages in terms of code readability and maintainability. By utilizing Go structs instead of raw SQL statements, GORM streamlines the coding process and makes it more intuitive.

This framework simplifies complex operations such as handling associations and transactions while significantly reducing boilerplate code, allowing for a greater focus on implementing business logic rather than managing repetitive database tasks.


Next Article
Setting Up Gorm With MySQL

L

lambahasky9
Improve
Article Tags :
  • Go Language
  • Databases
  • MySQL
  • mysql
  • Golang

Similar Reads

    How to Use Go with MySQL?
    MySQL is an open-source relational database management system based on Structured Query Language(SQL). It is a relational database that organizes data into one or more tables in which data are related to each other. Database Driver: A Database Driver implements a protocol for a database connection.
    4 min read
    Setting up Google Cloud SQL with Flask
    Setting up a database can be very tricky, yet some pretty simple and scalable solutions are available and one such solution is Google Cloud SQL. Cloud SQL is a fully-managed database service that makes it easy to set up, maintain, and administer your relational PostgreSQL and MySQL databases in the
    6 min read
    MySQL Security
    MySQL is one crucial database system that aids in talking to and managing the storage of data for innumerable websites and applications. By that, the way you lock your front door to protect the house, the same way you secure your MySQL Database in the hope that in case your data is hacked, only conc
    5 min read
    MySQL USE Statement
    MySQL is a very flexible and user-friendly Database. The USE command is used when there are multiple databases and we need to SELECT or USE one among them. We can also change to another database with this statement. Thus, the USE statement selects a specific database and then performs queries and op
    4 min read
    MySQL CREATE USER Statement
    The CREATE USER statement in MySQL is an essential command used to create new user accounts for database access. It enables database administrators to define which users can connect to the MySQL database server and specify their login credentials.In this article, We will learn about MySQL CREATE USE
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences