Gen Guides

GEN 指南

GEN: 更友好 & 更安全 GORM 代码生成。


  • Idiomatic & Reusable API from Dynamic Raw SQL
  • 100% Type-safe DAO API without interface{}
  • Database To Struct follows GORM conventions
  • GORM under the hood, supports all features, plugins, DBMS that GORM supports


go get -u


在程序中使用 gen 非常简单,具体操作如下:

1. 在 Go 中写入配置

package main

import ""

// Dynamic SQL
type Querier interface {
// SELECT * FROM @@table WHERE name = @name{{if role !=""}} AND role = @role{{end}}
FilterWithNameAndRole(name, role string) ([]gen.T, error)

func main() {
g := gen.NewGenerator(gen.Config{
OutPath: "../query",
Mode: gen.WithoutContext|gen.WithDefaultQuery|gen.WithQueryInterface, // generate mode

// gormdb, _ := gorm.Open(mysql.Open("root:@("))
g.UseDB(gormdb) // reuse your gorm db

// Generate basic type-safe DAO API for struct `model.User` following conventions

// Generate Type Safe API with Dynamic SQL defined on Querier interface for `model.User` and `model.Company`
g.ApplyInterface(func(Querier){}, model.User{}, model.Company{})

// Generate the code

2. 生成代码

go run main.go

3. 在您的项目中使用生成的代码

import "your_project/query"

func main() {
// Basic DAO API
user, err := query.User.Where(u.Name.Eq("modi")).First()

// Dynamic SQL API
users, err := query.User.FilterWithNameAndRole("modi", "admin")

Platinum Sponsors

Gold Sponsors

Platinum Sponsors

Gold Sponsors