Using JSONB columns in GORM allows you to work with JSON data types in PostgreSQL seamlessly. With GORM, you can easily define and manipulate JSONB fields in your Go application.
GORM, Go, JSONB, PostgreSQL, ORM, database, handling JSON, Go programming
package main
import (
"encoding/json"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type User struct {
ID uint `gorm:"primaryKey"`
Name string `json:"name"`
Metadata json.RawMessage `json:"metadata" gorm:"type:jsonb"` // JSONB column
}
func main() {
dsn := "user=gorm dbname=gorm port=9920 sslmode=disable"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect to the database")
}
// Auto migrate the User structure
db.AutoMigrate(&User{})
// Example of inserting a record with JSONB data
metadata := map[string]interface{}{
"age": 30,
"hobbies": []string{"reading", "gaming"},
}
metadataJSON, _ := json.Marshal(metadata)
user := User{Name: "John Doe", Metadata: metadataJSON}
db.Create(&user)
// Example of querying a record
var fetchedUser User
db.First(&fetchedUser, user.ID)
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?