GORMというORMが超絶便利だった件

taka
taka
Aug 31, 2018 · 7 min read

GoでAPI Serverを開発していく過程で、最近始めてORMという存在を知りました。
自分用のメモの意味も込めて今回、GoのORMであるGORMでよく使う操作をまとめておこうと思います。

そもそもORMて何やねん?

オブジェクト関係マッピング(英: Object-relational mapping、O/RM、ORM)とは
データベースとオブジェクト指向プログラミング言語の間の非互換なデータを変換するプログラミング技法である。
オブジェクト関連マッピングとも呼ぶ。実際には、オブジェクト指向言語から使える「仮想」オブジェクトデータベースを構築する手法である。
オブジェクト関係マッピングを行うソフトウェアパッケージは商用のものもフリーなものもあるが、場合によっては独自に開発することもある。

オブジェクトへのデータ取得などの処理を透過的に行えるようになるので、煩雑になりがちなデータベースに関する処理の記述がスマートになり、また柔軟なアプリケーションの構築が可能となる

それでは、本題のGORMの操作

GORMの取得方法

https://github.com/jinzhu/gorm

go get github.com/jinzhu/gorm

使用するDBのドライバは取得しているものとします。
※この記事ではMysqlを使用します。

操作方法

RDBとの接続方法

import (
"time"

"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)

func GetDBConn() *gorm.DB {
db, err := gorm.Open(GetDBConfig())
if err != nil {
panic(err)
}

db.LogMode(true)
return db
}

func GetDBConfig() (string, string) {
DBMS := "mysql"
USER := "root"
PASS := ""
PROTOCOL := ""
DBNAME := "gorm-example"
OPTION := "charset=utf8&parseTime=True&loc=Local"

CONNECT := USER + ":" + PASS + "@" + PROTOCOL + "/" + DBNAME + "?" + OPTION

return DBMS, CONNECT
}

マイグレーション
マイグレーションは、定義したstructをAutoMigrateの引数に渡すことで、それに対応するテーブルの作成を行う。

// Model 
type Model struct {
ID uint `gorm:"primary_key" json:"id"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time `sql:"index" json:"-"`
}

// 人物を表す構造体
type Person struct {
Model
Name string
Age int
}

func main() {

db := GetDBConn()

// Personテーブルの作成
db.AutoMigrate(&Person{})

}

GORMによって作成されたテーブルは`persons`という名前で作成される。

SELECT

// Model 
type Model struct {
ID uint `gorm:"primary_key" json:"id"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time `sql:"index" json:"-"`
}

// 人物を表す構造体
type Person struct {
Model
Name string
Age int
}
var person Person
var persons []Person // 複数件取得する場合、構造体を配列にする
func main() {

db := GetDBConn()

// SELECT * FROM persons;
db.Find(&persons)

// SELECT * FROM persons ORDER BY id LIMIT 1;
db.First(&person)

// SELECT * FROM persons ORDER BY id DESC LIMIT 1;
db.Last(&person)

// SELECT * FROM persons WHERE id = 1;
db.First(&person, 1)

// SELECT * FROM persons WHERE name = 'Gopher';
db.Where("name = ?", "Gopher").Find(&person)

// SELECT * FROM persons WHERE name = 'Gopher' limit 1;
db.Where("name = ?", "Gopher").First(&person)

// SELECT * FROM persons WHERE name = 'Gopher' AND id >= 1;
db.Where("name = ? AND age >= ?", "Gopher", 1).Find(&persons)

// SELECT * FROM persons WHERE name = 'Gopher' OR age = 1;
db.Where("name = ?", "Gopher").Or("age = ?", 1).Find(&persons)

// SELECT * FROM persons WHERE name LIKE '%Go%';
db.Where("name like ?", "%Go%").Find(&persons)

// SELECT * FROM persons WHERE NOT(name = 'Gopher');
db.Not("name = ?", "Gopher").First(&person)

}

INSERT

// Model 
type Model struct {
ID uint `gorm:"primary_key" json:"id"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time `sql:"index" json:"-"`
}

// 人物を表す構造体
type Person struct {
Model
Name string
Age int
}
func main() {

db := GetDBConn()

var person = Person{Name: "Gopher", Age: 10}

// INSERT INTO persons("name","age") values('Gopher',10);
db.Create(&person)

}

UPDATE

// Model 
type Model struct {
ID uint `gorm:"primary_key" json:"id"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time `sql:"index" json:"-"`
}

// 人物を表す構造体
type Person struct {
Model
Name string
Age int
}
func main() {

db := GetDBConn()

db.First(&person)

person.Name = "ゴーファー"
person.ID = 99

// UPDATE persons SET name = 'ゴーファー', age = 99 updated_at = '2018-08-27 21:34:10' WHERE id=1;
db.Save(&person)
}

DELETE

func main() {

db := GetDBConn()

// DELETE FROM persons WHERE id = 1;
db.Delete(&person, 1)

}

GORMの操作をここで全て書くのは長くなるので、自分がこの辺よく使うなと思う部分のみ描きました。

詳しくGORMを知りたい方のために自分もよく使うサイトを紹介しておきます。
http://gorm.io/docs/
http://doc.gorm.io/
https://godoc.org/github.com/jinzhu/gorm

taka

Written by

taka

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade