您的位置 首页 golang

根据mysql表结构自动生成go struct

当我们用Go做数据库相关操作时,编写出和表对应的结构体是必做的事情,例如

 type ServiceRecommend struct {
   Id              int64  `gorm:"id" json:"id"`                               // id
   ShopId          int64  `gorm:"shop_id" json:"shop_id"`                     // shopID
   MarketServiceId int64  `gorm:"market_service_id" json:"market_service_id"` // 服务市场服务id
   Status          int64  `gorm:"status" json:"status"`                       // 推荐状态 1推荐 2取消推荐
   CreateBy        string `gorm:"create_by" json:"create_by"`                 // 创建人
   CreateTime      string `gorm:"create_time" json:"create_time"`             // 创建时间
   UpdateBy        string `gorm:"update_by" json:"update_by"`                 // 更新人
   UpdateTime      string `gorm:"update_time" json:"update_time"`             // 更新时间
}
  

这里简单介绍一下gorm和json字段。其中用gorm设置key的特性,如主键、长度等。json用来设置在struct作为json输出的时候,key的名称,如果不设置,默认与导出字段一致。

编写struct没什么技术含量,完全是重复工作。基于重复事情做三次,就要自动化的原则,从github上找到了解决方案。

其实对于解决这个问题的代码挺多,这里提供相对方便且功能强大的,代码库github.com/gohouse/converter,使用方法:

 package main
import (
   "fmt"
   "github.com/gohouse/converter"
)
func main() {
   err := converter.NewTable2Struct().
      SavePath("./model.go").
      Dsn("用户名:密码@tcp(IP:端口号)/数据库名?charset=utf8").
      TagKey("gorm").
      EnableJsonTag(true).
      Table("表名").
      Run()
   fmt.Println(err)
}
  

SavePath为输出结果存放文件

DSN用于配置数据库的信息

TagKey用于配置Tag,此处写为gorm

EnableJsonTag用于确认是否输出时有json标签

Table用于指定表,如果不写则输出库中的所有表

文章开始处的struct就是用该代码生成的,是不是方便了很多。

总结

程序员理应是懒人,需要用技术来提高效率,做到虽然懒但是也能开心生活。

资料

最后

大家如果喜欢我的文章,可以关注我的公众号(程序员麻辣烫)

我的个人博客为:

往期文章回顾:

设计模式

  1. Go设计模式(5)-类图符号表示法
  2. Go设计模式(4)-代码编写优化
  3. Go设计模式(4)-代码编写
  4. Go设计模式(3)-设计原则
  5. Go设计模式(2)-面向对象分析与设计
  6. Go设计模式(1)-语法

语言

  1. Go工具之generate
  2. Go单例实现方案
  3. Go通道实现原理
  4. Go定时器实现原理
  5. Beego框架使用
  6. Golang源码BUG追查
  7. Gin框架简洁版
  8. Gin源码剖析

架构

  1. 支付接入常规问题
  2. 限流实现2
  3. 秒杀系统
  4. 分布式系统与一致性协议
  5. 微服务之服务框架和注册中心
  6. 浅谈微服务
  7. 限流实现1
  8. CDN请求过程详解
  9. 常用缓存技巧
  10. 如何高效对接第三方支付
  11. 算法总结

存储

  1. MySQL开发规范
  2. Redis实现分布式锁
  3. 事务原子性、一致性、持久性的实现原理
  4. InnoDB锁与事务简析

网络

  1. HTTP2.0基础教程
  2. HTTPS配置实战
  3. HTTPS连接过程
  4. TCP性能优化

读书笔记

  1. 原则
  2. 资治通鉴
  3. 敏捷革命
  4. 如何锻炼自己的记忆力
  5. 简单的逻辑学-读后感
  6. 热风-读后感
  7. 论语-读后感
  8. 孙子兵法-读后感

思考

  1. 为动员一切力量争取抗战胜利而斗争
  2. 反对自由主义
  3. 实践论
  4. 评价自己的标准
  5. 服务端团队假期值班方案
  6. 项目流程管理
  7. 对项目管理的一些看法
  8. 对产品经理的一些思考
  9. 关于程序员职业发展的思考
  10. 关于代码review的思考
  11. Markdown编辑器推荐-typora

文章来源:智云一二三科技

文章标题:根据mysql表结构自动生成go struct

文章地址:https://www.zhihuclub.com/98963.shtml

关于作者: 智云科技

热门文章

评论已关闭

36条评论

  1. Your health is more important than your feelings, so don t be embarrassed or hesitant doctors see and treat thousands of patients every year for ED and recommend Viagra

  2. A psychologic cause should be suspected in young healthy men with abrupt onset of erectile dysfunction ED , particularly if onset is associated with a specific emotional event or if the dysfunction occurs only in certain settings

  3. We strive to provide you with a high quality community experience. Going to test Friday with an first response.

  4. The panel advises avoiding oral step- down to nitrofurantoin, fosfomycin, doxycycline, or amoxicillin- clavulanate for AmpC- E bloodstream infections. Contraindicated 1 oxcarbazepine decreases levels of rilpivirine by affecting hepatic intestinal enzyme CYP3A4 metabolism.

  5. Therefore, once diagnosis of LCIS is established via CNB, whether further excision is necessary or not is a matter for argument International Journal of Indigenous Health 10

  6. Act D 10 Ојg ml was added to AML12 cells infected with Ad ERRОі Hi Everyone I haven t been on in awhile but I finished chemo at the end of August and started Tamoxifen

  7. The pharmacy dispensing database was used to capture use of all sleep aids name, date of initiation, days supplied in the health plan s formulary lorazepam, trazodone, doxepin, flurazepam, temazepam, triazolam, eszopiclone, zaleplon, zolpidem, and suvorexant Thanks to everyone for the replies and discussions

  8. Moreover, the Fallopian tubes are typically 8 inches long, and women who have a minimum of 4 inches of tube after the re- joining procedure have the highest pregnancy success rates after a tubal reversal procedure

  9. The knee jerk response is to administer further, if not larger, doses of furosemide We investigated the preventive effect of an active metabolite of tamoxifen, 4 hydroxytamoxifen 4 OH TAM, on capsular contracture

  10. Tamoxifen reduces the risk of breast cancer recurrence by approximately a half and the risk of mortality by approximately a quarter

  11. Part of the non compliance is that not everyone took the recommended drugs and a majority reported missing doses

  12. The most important one I think is that you EDUCATE yourself They compared true acupuncture versus sham acupuncture three RCTs, true acupuncture versus relaxation one RCT, true acupuncture versus clomiphene one RCT, low frequency electroacupuncture versus physical exercise or no intervention one RCT and true acupuncture versus Diane 35 two RCTs

  13. And third about whether Osphena, which mimics estrogen and has similar known downsides, may also be a back door, off label replacement for hormone replacement therapy, which was discredited a decade ago

  14. Hence the name of myxedema coma itself can be misleading Medications are stopped or substituted in order of their likelihood of causing DIT, guided by compilations of the most commonly implicated medications and their levels of evidence Table 2

  15. Franklyn DltgETBHBDWPA 6 17 2022 As pointed out in the editorial, 12 differences exist in product summaries for tamoxifen, with some manufacturers listing reduced efficacy caused by concurrent use of CYP2D6 inhibitors and others not

  16. If IUI still isn t helping you conceive, you may move on to try in vitro fertilization IVF Leslie, 2021 staff told me the gender of our embryos when we said we didn t want to know

  17. Here we review in comparison to the neuropathological effects of HIV 1 the available information on neuropsychiatric adverse effects and neurotoxicity of clinically used ARV and cART

  18. medroxyprogesterone que es ciprofloxacina para sirve This was a senseless and sad murder where a soldier killed a fellow soldier for no reason, said Pierce County Prosecutor Mark Lindquist in a written statement

  19. DETROL LA is also contraindicated in patients with known hypersensitivity to the drug or its ingredients, or to fesoterodine fumarate extended release tablets which, like DETROL LA, are metabolized to 5 hydroxymethyl tolterodine see WARNINGS AND PRECAUTIONS BUN Blood Urea Nitrogen Tests measure the amount of urea nitrogen in the blood and are typically ordered to evaluate kidney function

  20. On the basis of these results, it could be hypothesized that loss of Fas with the retention of FasL in p53 null tumors would result in enhanced survival both due to reduced self apoptotic elimination as well as diminished immune mediated killing This will help ensure that the active ingredients are broken down properly in the stomach and distributed in the bloodstream

  21. 2010 found that in a cohort of stone formers, those with hypernatriuresis were more likely to develop stones in 3 year follow up

网站地图