Wednesday, March 20, 2024

Golang Tutorial: How to Use GORM as an Simple Database ORM


GORM emerges as a preferred choice for backend development due to its seamless database querying capabilities and comprehensive documentation, making it an ideal companion for both seasoned developers and newcomers.

GORM boasts support for various databases, including Mysql, Sqlite, Postgres, SqlServer, and Clickhouse. Moreover, its extensibility allows for custom driver integration, ensuring compatibility with diverse database systems. In this article, we'll unravel the core features of GORM, focusing on MySQL as our database of choice.

CRUD Operations

Let's kick off our exploration with CRUD (Create, Read, Update, Delete) operations in GORM, pivotal for database manipulation in application development.

Create Query:

Creating records in GORM is straightforward. Here's how you can create single or multiple records:

// Single record creation

post := entity.Post{

    Title: title,

    Body:  body,

    Slug:  strings.Replace(title, " ", "-", -1),

}

result := db.Create(&post)


// Batch inserts

posts := []entity.Post{

    {

        Title: title,

        Body:  body,

        Slug:  strings.Replace(title, " ", "-", -1),

    },

    // Additional records...

}

result := db.Create(&posts)

Update Query:

Updating records involves fetching the record and modifying its attributes, followed by saving the changes:

// Fetching a record for update

post := entity.Post{}

db.First(&post)


// Modifying attributes

post.Title = "Loremp Ipsum Title Updated"

post.Body = "Loremp Ipsum Body Updated"

db.Save(&post)

Delete Query:

Deleting records in GORM is a breeze:

// Deleting a single record

db.Delete(&entity.Post{}, 1)


// Deleting records with multiple primary keys

db.Delete(&entity.Post{}, []int{1,2,3})


// Deleting records based on conditions

db.Where("title LIKE ?", "%should deleted%").Delete(&entity.Post{})

Read Query:

Reading records in GORM offers flexibility and efficiency:

// Fetching a single record

post := entity.Post{}

err := db.First(&post, 1).Error

if err != nil {

    panic(err)

}


// Fetching multiple records

posts := []entity.Post{}

db.Find(&posts)


// Additional query examples...

Conclusion

In this article, we've embarked on a journey to uncover the powerful features of GORM for database operations in Go. From CRUD operations to advanced querying functionalities, GORM simplifies database interaction, empowering developers to focus on building robust applications.

I hope this article serves as a valuable resource in your journey with GORM and Golang development. Stay tuned for more insightful articles, and until next time, happy coding!

0 comments:

Post a Comment