GoLand的Golang ORM辅助插件使用指南

GoLand的Golang ORM辅助插件使用指南 一个GoLand插件,能自动提供数据库字段自动补全、标签,并为编写ORM代码生成结构体。支持:Gorm、Xorm、Beego、GoFrame等。

功能

  • ORM代码补全。
  • 支持SQL到结构体的转换。
  • 支持Go ORM标签实时模板。
  • 更多功能等待发现和改进…

GitHub

GitHub - maiqingqiang/go-orm-helper: 🚀🚀 A GoLand plugin that automatically…

🚀🚀 一个GoLand插件,能自动提供数据库字段补全、标签,并为编写ORM代码生成结构体。支持:Gorm、Xorm、Beego、GoFrame等。⭐️ 点赞支持我们的工作!一个为了让…


更多关于GoLand的Golang ORM辅助插件使用指南的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于GoLand的Golang ORM辅助插件使用指南的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


这是一个非常实用的GoLand插件,对于使用ORM进行数据库开发的Gopher来说,能显著提升效率。下面针对其核心功能进行说明和示例演示。

1. 数据库字段自动补全与标签生成

安装插件并配置数据库连接后,在结构体字段后输入ORM标签时,插件会提供数据库字段名的补全建议,并自动生成完整的标签。

示例: 假设数据库有 users 表,包含 id, username, created_at 等字段。

type User struct {
    ID        uint      `gorm:"column:id;primaryKey"` // 输入 `gorm:"` 后插件会提示字段名
    Username  string    `gorm:"column:username"`      // 自动补全 column:username
    CreatedAt time.Time `gorm:"column:created_at"`    // 自动生成 created_at 的标签
}

对于Xorm,同样支持:

type User struct {
    Id        int64     `xorm:"'id' pk autoincr"` // 插件提示字段并生成标签
    UserName  string    `xorm:"'username'"`
    CreatedAt time.Time `xorm:"'created_at'"`
}

2. SQL到结构体的转换

在GoLand中选中SQL建表语句,右键使用插件的转换功能,可直接生成对应的Go结构体。

示例SQL:

CREATE TABLE `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `price` decimal(10,2) DEFAULT NULL,
  `in_stock` tinyint(1) DEFAULT '1',
  PRIMARY KEY (`id`)
);

插件转换生成的Go结构体(以Gorm为例):

type Product struct {
	ID      int     `gorm:"column:id;primaryKey;autoIncrement"`
	Name    string  `gorm:"column:name;not null"`
	Price   float64 `gorm:"column:price;type:decimal(10,2)"`
	InStock bool    `gorm:"column:in_stock;type:tinyint(1)"`
}

3. ORM代码补全

编写ORM查询时,插件能提供链式方法补全和模型字段补全。

示例:

db.Where("", ).First(&user)
//         ^ 输入时,插件会提示 `users` 表的字段如 `id`, `username`
db.Select([]string{}).Find(&users)
//           ^ 输入时,插件会提示字段列表供选择

4. 实时模板

插件内置了常用ORM代码的实时模板(Live Template),通过缩写快速生成代码片段。

示例:

  • 输入 gormm 按Tab键,可能生成完整的Gorm模型定义结构。
  • 输入 xormq 按Tab键,可能生成Xorm的查询条件代码块。
// 输入 gormm 后生成的结构体模板
type Model struct {
    ID        uint           `gorm:"primaryKey"`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt gorm.DeletedAt `gorm:"index"`
}

配置与使用要点

  1. 安装插件:在GoLand的插件市场搜索 go-orm-helper 进行安装。
  2. 数据源配置:在IDE的数据库工具窗口添加你的数据库连接(MySQL、PostgreSQL等),插件依赖此连接获取元数据进行补全。
  3. 项目依赖:确保你的Go项目已经正确引入了相应的ORM库(如 gorm.io/gorm),这样插件的标签补全和代码生成才能对齐ORM的语法。

这个插件通过深度集成GoLand和数据库,将ORM开发中繁琐的字段映射、标签编写工作自动化,是提升Go数据库编程体验的利器。

回到顶部