安装
首先命令行安装 xorm
工具:
go get xorm.io/xorm
xorm 工具
测试 xorm
是否安装成功/查看 xorm
命令说明,使用 xorm help
$ xorm help
xorm is a database tool based xorm package.
Version:
0.3.0324
Usage:
xorm command [arguments]
The commands are:
reverse reverse a db to codes
shell a general shell to operate all kinds of database
dump dump database all table struct's and data to standard output
driver list all supported drivers
source source execute std in to datasourceName
Use "xorm help [command]" for more information about a command.
复制代码
以上列举了 xorm
各个命令说明:
- reverse 映射数据表结构到代码
- shell 命令行,用于操作各类型数据库
- dump 转储数据库所有表结构和数据
- driver 列举所有支持的驱动程序
- source 源数据录入数据库
其中最常用的是 reverse
数据库结构映射命令, 将数据表结构映射成对应结构体
下面是 reverse
命令 说明
$ xorm help reverse
usage: xorm reverse [-s] driverName datasourceName tmplPath [generatedPath] [tableFilterReg]
according database's tables and columns to generate codes for Go, C++ and etc.
-s Generated one go file for every table
driverName[数据库驱动名] Database driver name, now supported four: mysql mymysql sqlite3 postgres
datasourceName[数据库链接] Database connection uri, for detail infomation please visit driver's project page
tmplPath[生成结构体模板路径] Template dir for generated. the default templates dir has provide 1 template
generatedPath[输出路径,默认为models] This parameter is optional, if blank, the default value is models, then will
generated all codes in models dir
tableFilterReg[表过滤] Table name filter regexp
复制代码
于是乎 数据库结构映射命令 例子如下:
xorm reverse mysql “root:root@tcp(0.0.0.0:3306)/demo?charset=utf8” models/templates/xorm
配置生成结构体模板
在项目根目录下建立models/templates/xorm
文件夹,在文件夹下建立config
和template.go.tpl
文件。
config 开启数据库结构反转
lang=go
genJson=1
prefix=
复制代码
template.go.tpl 结构体模板代码
package {{.Models}}
{{$ilen := len .Imports}}
{{if gt $ilen 0}}
import (
{{range .Imports}}"{{.}}"{{end}}
)
{{end}}
{{range .Tables}}
type {{Mapper .Name}} struct {
{{$table := .}}
{{range .ColumnsSeq}}{{$col := $table.GetColumn .}} {{Mapper $col.Name}} {{Type $col}} {{Tag $table $col}}
{{end}}
}
{{end}}
复制代码
以上模板内容可以根据自己实际情况调整修改
最后执行命令,反转数据库结构,生成代码
xorm reverse mysql root:root@/demo?charset=utf8 models/templates/xorm
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END