GithubHelp home page GithubHelp logo

jkylin / gobatis Goto Github PK

View Code? Open in Web Editor NEW

This project forked from mei-rune/gobatis

0.0 1.0 0.0 646 KB

An easy ORM tool for Golang, support MyBatis-Like XML template SQL

Home Page: https://runner-mei.github.io/GoBatis

Go 99.97% Batchfile 0.03%

gobatis's Introduction

GoBatis

GoDoc Travis Build Status GitHub tag (latest SemVer) Coverage Status Appveyor Build status

Introduction

An easy ORM tool for Golang, support MyBatis-Like XML template SQL

待完成的任务

  1. 重构 parser
  2. 对象继承的实现
  3. 延迟加载的实现

已知 bug

  1. 当 sql 中含有 xml 标签时 < 号需要转义为 &lt; ,而不含 xml 标签时&lt; 又不转义为 < , 这很不一致。

和 MyBatis 的区别

GoBatis 就是对 MyBatis 的简单模仿。 但有下列不同

  1. 动态 sql 语句的格式

    我实现一个和 mybatis 类似的 if, chose, foreach, set 和 where 之类的 xml 基本实现,同时也支持 go template 来生成 sql。

  2. 自动生成 sql 语句

    MyBatis 是不会自动生成 sql 语句的, 我觉得能像大部份的 orm 一样能生成 sql 的话,可以省很多工作 请见 SQL 自动生成

基本思路

  1. 用户定义结构和接口
  2. 在接口的方法上定义 sql (可以在 xml 中或方法的注释中)
  3. 用工具生成接口的实现
  4. 创建接口的实例并使用它

Usage

注意, gobatis 也支持 xml, 请见 example_xml 目录

  1. install gobatis tools.

    go get -u -v github.com/runner-mei/GoBatis/cmd/gobatis

  2. Define a struct, interface and comment methods with SQLs and Variables, then write a directive //go:generate gobatis user.go.

//go:generate gobatis user.go
package example

import (
  "time"
)

type AuthUser struct {
  ID        int64      `json:"id"`
  Username  string     `json:"username"`
  Phone     string     `json:"phone"`
  Address   *string    `json:"address"`
  Status    uint8      `json:"status"`
  BirthDay  *time.Time `json:"birth_day"`
  CreatedAt time.Time  `json:"created_at"`
  UpdatedAt time.Time  `json:"updated_at"`
}

type UserDao interface {
  // @postgres insert into auth_users(username, phone, address, status, birth_day, created_at, updated_at)
  // values (#{username},#{phone},#{address},#{status},#{birth_day},CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) returning id
  //
  // @default insert into auth_users(username, phone, address, status, birth_day, created_at, updated_at)
  // values (#{username},#{phone},#{address},#{status},#{birth_day},CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
  Insert(u *AuthUser) (int64, error)
}
  1. After that, run go generate ./... , user.gobatis.go is generated
// Please don't edit this file!
package example

import (
  "errors"

  gobatis "github.com/runner-mei/GoBatis"
)

func init() {
  gobatis.Init(func(ctx *gobatis.InitContext) error {
    { //// UserDao.Insert
      if _, exists := ctx.Statements["UserDao.Insert"]; !exists {
        sqlStr := "insert into auth_users(username, phone, address, status, birth_day, created_at, updated_at)\r\n values (#{username},#{phone},#{address},#{status},#{birth_day},CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
        switch ctx.Dialect {
        case gobatis.ToDbType("mssql"):
          sqlStr = "insert into auth_users(username, phone, address, status, birth_day, created_at, updated_at)\r\n output inserted.id\r\n values (#{username},#{phone},#{address},#{status},#{birth_day},CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
        case gobatis.ToDbType("postgres"):
          sqlStr = "insert into auth_users(username, phone, address, status, birth_day, created_at, updated_at)\r\n values (#{username},#{phone},#{address},#{status},#{birth_day},CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) returning id"
        }
        stmt, err := gobatis.NewMapppedStatement(ctx, "UserDao.Insert",
          gobatis.StatementTypeInsert,
          gobatis.ResultStruct,
          sqlStr)
        if err != nil {
          return err
        }
        ctx.Statements["UserDao.Insert"] = stmt
      }
    }
  })
}

func NewUserDao(session gobatis.SqlSession) UserDao {
  return &UserDaoImpl{session: session}
}

type UserDaoImpl struct {
  session gobatis.SqlSession
}

func (impl *UserDaoImpl) Insert(u *AuthUser) (int64, error) {
  return impl.session.Insert("UserDao.Insert",
    []string{
      "u",
    },
    []interface{}{
      u,
    })
}

...
  1. use UserDao
  factory, err := gobatis.New(&gobatis.Config{DriverName: tests.TestDrv,
    DataSource: tests.TestConnURL,
    // XMLPaths: []string{"example/test.xml"},
    })
    
  userDao := NewUserDao(factory.SessionReference())
  id, err := userDao.Insert(&insertUser)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println("insert success!")

  u, err := userDao.Get(id)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println("fetch user from database!")

  _, err = userDao.Delete(id)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println("delete success!")

注意

GoBatis 是基于 osm 的基础上修改来的,goparser 则是在 light 的基础上修改来的, reflectx 则从 sqlx 拷贝过来的

gobatis's People

Contributors

mei-rune avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.