GORMとは
Go言語のORMライブラリです。
特徴
- フル機能ORM
- アソシエーション(Has One, Has Many, Belongs To, Many To Many, Polymorphism, Single-table inheritance)
- フック (Before/After Create/Save/Update/Delete/Find)
Preload,Joinsを使ったイーガーロード- トランザクション、ネスティング、セーブポイント、セーブポイントへのロールバック
- Context、プリペアドステートメント、ドライラン
- Batch Insert, FindInBatches, Find/Create with Map, CRUD with SQL Expr and Context Valuer
- SQL Builder, Upsert, Locking, Optimizer/Index/Comment Hints, Named Argument, SubQuery
- Composite Primary Key, Indexes, Constraints
- オートマイグレーション
- ロガー
- Extendable, flexible plugin API: Database Resolver (Multiple Databases, Read/Write Splitting) / Prometheus…
- すべての機能に付属するテストコード
- デベロッパーフレンドリー
インストール
GORM V1
$ go get -u github.com/jinzhu/gorm
GORM V2
$ go get -u gorm.io/gorm
GORM初期設定(V1基準)
package controllers
import (
“goblog/app/models”
“github.com/jinzhu/gorm” // 1.gorm パッケージをインポート
“github.com/revel/revel”
)
var (
db gorm.DB
)
// 2.GormController定義
type GormController struct {
*revel.Controller
Txn *gorm.DB
}
// 3.データベースの初期化
func InitDB() {
var (
driver, spec string
found bool
)
// Read configuration.
if driver, found = revel.Config.String(“db.driver”); !found {
revel.ERROR.Fatal(“No db.driver found.”)
}
if spec, found = revel.Config.String(“db.spec”); !found {
revel.ERROR.Fatal(“No db.spec found.”)
}
// Open a connection.
var err error
db, err = gorm.Open(driver, spec)
if err != nil {
revel.ERROR.Fatal(err)
}
// Enable Logger
db.LogMode(true)
migrate()
}
// 4.テーブル生成
func migrate() {
db.AutoMigrate(&models.Post{}, &models.Comment{})
}
// 5.トランザクション設定
// Begin a transaction
func (c GormController) Begin() revel.Result {
c.Txn = db.Begin()
return nil
}
// Rollback if it’s still going (must have panicked).
func (c GormController) Rollback() revel.Result {
if c.Txn != nil {
c.Txn.Rollback()
c.Txn = nil
}
return nil
}
// Commit the transaction.
func (c *GormController) Commit() revel.Result {
if c.Txn != nil {
c.Txn.Commit()
c.Txn = nil
}
return nil
}
- gormを利用するためにgormパッケージをインポート
- コントローラータイプで使用するGormController定義。GormControllerはRevelの基本コントローラーである「*revel.Controller」をエンベデッドフィールドに指定し、「*revel.Controller」の全ての機能をそのまま使用できるようにしてくれます。
- Revelプロジェクトの設定ファイルapp.confファイルからrevel.Config.String()でデータベースの設定情報を持ってきてコネクションを生成します。
- Webアプリケーションの機能時にテーブルが生成されます。
- データ処理時に、トランザクション管理のため、作成します。
package controllers
import "github.com/revel/revel"
// 6.アプリケーションの初期化ロジックを登録
func init() {
revel.OnAppStart(InitDB)
revel.InterceptMethod((*GormController).Begin, revel.BEFORE)
revel.InterceptMethod((*GormController).Commit, revel.AFTER)
revel.InterceptMethod((*GormController).Rollback, revel.FINALLY)
}
6. init()関数で初期化する初期化ロジックを登録します。GormControllerの全てのアクションにBegin、Commit、Rollbackを処理するようにインタセプターを登録します。
