gorm概述与快速入门

特性

  • 全功能 ORM
  • 关联 (Has One,Has Many,Belongs To,Many To Many,多态,单表继承)
  • Create,Save,Update,Delete,Find 中钩子方法
  • 支持 PreloadJoins 的预加载
  • 事务,嵌套事务,Save Point,Rollback To Saved Point
  • Context、预编译模式、DryRun 模式
  • 批量插入,FindInBatches,Find/Create with Map,使用 SQL 表达式、Context Valuer 进行 CRUD
  • SQL 构建器,Upsert,数据库锁,Optimizer/Index/Comment Hint,命名参数,子查询
  • 复合主键,索引,约束
  • Auto Migration
  • 自定义 Logger
  • 灵活的可扩展插件 API:Database Resolver(多数据库,读写分离)、Prometheus…
  • 每个特性都经过了测试的重重考验
  • 开发者友好

安装

go get -u gorm.io/gorm
go get -u gorm.io/driver/sqlite

  

快速入门

package main

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

const (
	host   = "xxx"
	port   = 8000
	user   = "username"
	passwd = "xxx"
	db     = "topgoer_gorm"
	other  = "charset=utf8mb4&parseTime=True&loc=Local"
)

type Product struct {
	gorm.Model
	Code string
	Price uint
}

func MyPrint(p interface{}) {
	fmt.Printf("type: %T\tvalue: %v\n", p, p)
}

func main() {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?%s", user, passwd, host, port, db, other)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("conn mysql fail", err)
		return
	}
	sqlDb, _ := db.DB()
	defer sqlDb.Close()  // 关闭链接

	// 自动检查User结构是否发生变化,变化则进行迁移
	db.AutoMigrate(&Product{})

	// create
	//db.Create(&Product{Code: "D42", Price: 100})
	//db.Create(&Product{Code: "D43", Price: 200})

	// read
	var product Product
	db.First(&product, 1)  // 根据整型主键查找
	MyPrint(product)
	db.First(&product, "code = ?", "D43")  // 查找code字段为D43的记录
	MyPrint(product)

	// update 更新单个字段
	db.Model(&product).Update("price", 300)  // 将product的price更新为300
	MyPrint(product)

	// updates 更新多个字段
	db.Model(&product).Updates(Product{Code: "F43", Price: 400})  // 仅更新非零值字段
	MyPrint(product)
	db.Model(&product).Updates(map[string]interface{}{
		"Code": "F44",
		"Price": 500,
	})
	MyPrint(product)

	// delete,  注意:此处必须是结构体指针,不能是结构体实例
	db.Delete(new(Product), 1)  // 删除product

}

  

参考链接:https://gorm.io/zh_CN/docs/index.html

posted @ 2021-11-16 10:52  专职  阅读(143)  评论(0编辑  收藏  举报