go项目使用gentool生成model的gen.go问题

发布于:2025-02-11 ⋅ 阅读:(83) ⋅ 点赞:(0)

Gen Tool 是一个没有依赖关系的二进制文件,可以用来从数据库生成结构。

使用方法:

go install gorm.io/gen/tools/gentool@latest

在项目根目录,执行连接的数据库中指定某几张表结构生成数据库model层

gentool -dsn "root:123456@tcp(localhost:3306)/go-demo-2025?charset=utf8mb4&parseTime=True&loc=Local" -tables "demo,user" -outPath "./gen_model/dao/query"

操作示例:

image-20250102171013926

生成的model文件如下:

image-20250102170943384

现在遇到的问题:使用此方法,如果只指定其中几个表,那么其它已有的表的gen.go会被覆盖。

比如,现在我再次使用上面的命令,生成一个新的表:

gentool -dsn "root:123456@tcp(localhost:3306)/go-demo-2025?charset=utf8mb4&parseTime=True&loc=Local" -tables "common_config" -outPath "./gen_model/dao/query"

此时,刚才生成的 gen.go 里面之前生成的表的结构体就没有了,程序也就跑不起来了:

image-20250102171300798

出现这个情况,可能是这个工具的一个bug。如果改为生成全部表名,也不太方便,因为有时候其他小伙伴改动了某个表,不能随着当前版本上线,就会很被动。除非每次执行这个命令的时候,都要把之前已经有的数据表名都带上,会很麻烦。

目前暂未找到合适的解决方案,因此改为下面的方式:

在项目根目录下面创建 gen.tool 文件,写入内容如下:

version: "0.1"
database:
  dsn : "root:123456@tcp(localhost:3306)/go-demo-2025?charset=utf8mb4&parseTime=True&loc=Local"
  db  : "mysql"
  tables  : ["demo","user","common_config"]
  outPath :  "./gen_model/dao/query"
  # 默认: gen.go
  outFile :  ""
  # generate unit test for query code
  withUnitTest  : false
  # generated model code's package name
  modelPkgName  : ""
  # generate with pointer when field is nullable
  fieldNullable : false
  # generate field with gorm index tag
  fieldWithIndexTag : false
  # generate field with gorm column type tag
  fieldWithTypeTag  : false

这样一来,如果需要生成新的数据表的model,只需要在 tables : 后面追加你想要新增生成的表名,已有的表名不要动!

然后在项目根目录执行下面的命令就好了:

gentool -c "./gen.tool"

这样生成的多个数据表的model就没有问题了。

image-20250102172120450

参考资料:

https://gorm.io/zh_CN/gen/gen_tool.html
https://insight.xiaoduoai.com/intelligent-frontiers/tech/gorm-use-gentool-tool-to-generate-structure-from-database.html