第九单元 ORM

第九单元 ORM

一、ORM介绍
1.ORM:Object Relational Mapping 对象关系映射
2.作用:是把对对象的增删改查操作转换为sql
3.支持的数据库驱动
mysql sqlite3 postgresql oracle

4.优点
4.1 支持golang语言的所有数据类型,比如:字符串,整型,布尔等
4.2 学习比较简单,采用的是CRUD风格
4.3 表关联:one2one,one2many,many2many
4.4 跨库查询
4.5 使用原生SQL查询
4.6 比较稳定,性能好

二、ORM的使用

2.1 安装ORM
go get github.com/astaxie/beego/orm


2.2 ORM增删改查演示

orm.RegisterDataBase("default", "mysql", "root:root@tcp(127.0.0.1:3306)/1712a")
orm.RunSyncdb("default", false, true) //修改model字段自动同步数据表


步骤1.main.go
package main

import (
	_ "1803a_chapter9/routers"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

//初始化函数定义
func init() {
	//注册mysql驱动
	orm.RegisterDataBase("default", "mysql", "root:root@tcp(127.0.0.1:3306)/1803a")
   //同步结构体到数据表	
   orm.RunSyncdb("default", false, true) 
}

func main() {
	beego.Run()
}



步骤2.路由定义 routes/router.go
package routers

import (
	"1803a_chapter9/controllers"

	"github.com/astaxie/beego"
)

func init() {
	beego.Router("/", &controllers.MainController{})

	beego.Router("/add", &controllers.MemberController{}, "post:AddMember")
	beego.Router("/details/:id", &controllers.MemberController{}, "get:Details")
	beego.Router("/list", &controllers.MemberController{}, "get:MemberList")
	beego.Router("/update/:id", &controllers.MemberController{}, "put:UpdateMember")
	beego.Router("/delete/:id", &controllers.MemberController{}, "delete:DeleteMember")

}




步骤3.模型定义 Models.go
// Model
package models

import (
	"github.com/astaxie/beego/orm"
)

type Member struct {
	Id    int    `orm:"column(id);size(50) auto" description:"id"`
	Name  string `orm:"column(name);size(50)" description:"名称"`
	Email string `orm:"column(email);size(50)" description:"邮箱"`
	Age   int    `orm:"column(age);size(4)" description:"年龄"`
}

func init() {
	orm.RegisterModel(new(Member))) //注册模型
}


步骤4.控制器定义 controllers/memberController.go
package controllers

import (
	"1803a_chapter9/models"
	"strconv"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type MemberController struct {
	beego.Controller
}

//会员信息添加
func (c *MemberController) AddMember() {

	reJson := make(map[string]interface{})
	c.Data["json"] = reJson
	defer c.ServeJSON()
	o := orm.NewOrm()
	var member models.Member
	member.Name = c.GetString("name")
	member.Email = c.GetString("email")
	member.Age, _ = c.GetInt("age", 18)

	if member.Name == "" {
		reJson["message"] = "用户名不能为空"
		reJson["status"] = "failed"
		return
	}

	_, err := o.Insert(&member)
	if err == nil {
		reJson["status"] = "ok"
		reJson["message"] = "添加成功"
	} else {
		reJson["status"] = "faild"
		reJson["message"] = "添加失败"
	}

}

//单个信息查询
func (c *MemberController) Details() {

	idStr := c.Ctx.Input.Param(":id")
	id, _ := strconv.Atoi(idStr)
	reJson := make(map[string]interface{})
	c.Data["json"] = reJson
	defer c.ServeJSON()

	var memberDetails []*models.Member
	om := orm.NewOrm()

	om.QueryTable("member").Filter("id", id).One(&memberDetails)
	if len(memberDetails) == 0 {
		reJson["status"] = "failed"
		reJson["message"] = "无此数据"
	} else {
		reJson["status"] = "ok"
		reJson["message"] = "查询成功"
	}

	reJson["data"] = &memberDetails

}

//列表查询
func (c *MemberController) MemberList() {

	reJson := make(map[string]interface{})
	c.Data["json"] = reJson
	defer c.ServeJSON()

	var memberList []*models.Member
	om := orm.NewOrm()

	om.QueryTable("member").All(&memberList)
	if len(memberList) == 0 {
		reJson["status"] = "failed"
		reJson["message"] = "无数据"
	} else {

		reJson["status"] = "ok"
		reJson["message"] = "查询成功"
	}

	reJson["data"] = &memberList

}

//单个更新
func (c *MemberController) UpdateMember() {
	idStr := c.Ctx.Input.Param(":id")
	id, _ := strconv.Atoi(idStr)
	o := orm.NewOrm()
	var member models.Member
	member.Id = id

	reJson := make(map[string]interface{})
	c.Data["json"] = reJson
	defer c.ServeJSON()

	if o.Read(&member) == nil {
		member.Name = c.GetString("name")
		member.Email = c.GetString("email")
		member.Age, _ = c.GetInt("age")
		if _, err := o.Update(&member); err == nil {
			reJson["status"] = "ok"
			reJson["message"] = "更新成功"

		}
	}

}

//删除单条信息
func (c *MemberController) DeleteMember() {

	idStr := c.Ctx.Input.Param(":id")
	id, _ := strconv.Atoi(idStr)

	o := orm.NewOrm()
	var member models.Member
	member.Id = id

	reJson := make(map[string]interface{})
	c.Data["json"] = reJson
	defer c.ServeJSON()

	if num, err := o.Delete(&member); err == nil {
		reJson["status"] = "ok"
		reJson["message"] = "删除成功"
	} else {
		reJson["status"] = "failed"
		reJson["message"] = "删除失败"
	}

}

  

posted @ 2020-07-28 08:09  flex_song  阅读(119)  评论(0编辑  收藏  举报