惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hacker News: Front Page
P
Palo Alto Networks Blog
T
ThreatConnect
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
T
True Tiger Recordings
P
Privacy & Cybersecurity Law Blog
B
Blog
IT之家
IT之家
Last Week in AI
Last Week in AI
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
C
Comments on: Blog
Microsoft Azure Blog
Microsoft Azure Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Microsoft Security Blog
Microsoft Security Blog
博客园 - 【当耐特】
N
News and Events Feed by Topic
NISL@THU
NISL@THU
腾讯CDC
雷峰网
雷峰网
Security Latest
Security Latest
李成银的技术随笔
M
Microsoft Research Blog - Microsoft Research
L
LangChain Blog
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Check Point Blog
Y
Y Combinator Blog
Recent Announcements
Recent Announcements
博客园 - Franky
N
News | PayPal Newsroom
V
V2EX
A
About on SuperTechFans
The Register - Security
The Register - Security
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google Online Security Blog
Google Online Security Blog
MyScale Blog
MyScale Blog
Cisco Talos Blog
Cisco Talos Blog
Vercel News
Vercel News
WordPress大学
WordPress大学
C
Cyber Attacks, Cyber Crime and Cyber Security
The Hacker News
The Hacker News
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
爱范儿
爱范儿
A
Arctic Wolf
L
LINUX DO - 最新话题
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

博客园 - 代码小伙

gin框架使用zap,在日志中加入trace_id Go使用base64Captcha生成字母验证码 GoFrame框架查询数据表时对字段取别名 GoFrame框架使用WherePri报错原因 GoFrame框架使用BindHandler设置路由失效的原因 GoFrame框架WebServer默认端口号是什么 GoFrame框架SetFileServerEnabled关闭静态服务不生效 vite修改端口号 用路由方式写一个通用的微信小程序校验文件验证 手机网页通过微信deeplink实现wap支付 position:sticky失效原因分析 mysql把一个表的字段赋值到另一张表 基于jquery的countdown插件实现毫秒倒计时 Vue打包代码如何部署在ThinkPHP项目里 保姆级教程,centos7安装erlang和rabbitmq Element Plus表单resetFields重置表单无效 thinkphp6通过中间件设置跨域 centos7安装jdk vue3中使用swiper6实现轮播
gorm使用gen自动生成模型和查询文件
代码小伙 · 2026-02-06 · via 博客园 - 代码小伙

项目使用的gin,整合的gorm,可以利用gen工具快速生成模型和查询文件

package database

import (
	"fmt"
	"sync"
	"time"

	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gen"
	"gorm.io/gorm"
)

var (
	instance *gorm.DB
	once     sync.Once
)

func Instance() *gorm.DB {
	once.Do(func() {
		var err error
		dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
			viper.GetString("database.user"),
			viper.GetString("database.pass"),
			viper.GetString("database.host"),
			viper.GetInt("database.port"),
			viper.GetString("database.name"))
  		instance, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
  		if err != nil {
  			panic("数据库连接失败")
  		}
	})

	if viper.GetBool("database.debug") {
		instance = instance.Debug()
	}

	generator := gen.NewGenerator(gen.Config{
		OutPath: "./app/dao",
		Mode: gen.WithDefaultQuery | gen.WithQueryInterface,
	})
	generator.UseDB(instance)
    // 非常重要,不加不生成文件!
	generator.ApplyBasic(generator.GenerateAllTable()...)
	generator.Execute()
	db, _ := instance.DB()
	db.SetMaxIdleConns(10)
	db.SetMaxOpenConns(100)
	db.SetConnMaxLifetime(time.Hour)
	db.SetConnMaxIdleTime(30 * time.Minute)
	return instance
}

需要注意以下几点:

  • 如果你想定义model目录的路径,目前只支持绝对路径(如写成./app/models这样的相对路径是不行的)或者通过设置OutPathModelPkgPath,可以实现自定义模型路径
  • model生成位置:取OutPath路径中的目录(如OutPath是./app/dao,则目录是./app),再拼接上ModelPkgPath(如不设置ModelPkgPath,默认就叫model),拼接后最终model会生成在./app/model
  • generator.ApplyBasic(generator.GenerateAllTable()...)必须有这句,否则不生成任何modelquery文件