Skip to content
A High Performance ORM SQL framework for Golang. same to Mybatis,Ibatis for go
Go Other
  1. Go 99.4%
  2. Other 0.6%
Branch: master
Clone or download
Latest commit f505d4a Aug 17, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.idea add test Nov 7, 2018
ast Update readme.md Aug 2, 2019
engines fix Apr 13, 2019
example 支持返回结果指针 May 18, 2019
lib/github.com delete mod Jul 27, 2019
tx fix Apr 24, 2019
utils fix bugs May 12, 2019
.gitignore 添加忽略 Feb 16, 2019
.travis.yml 修改go环境要求 Jan 21, 2019
CallBack.go add callback support Apr 18, 2019
DataSourceRouter.go 事务传播行为改为默认单协程模型(因为go标准库的http模块,基于标准库的http框架例如beego等handle都属于同一线程处理的)用… Apr 28, 2019
ElementType.go 添加模板概念测试 Feb 11, 2019
ExpressionEngineLexerCache.go 优化架构性能 Feb 16, 2019
ExpressionEngineLexerCacheable.go 新增 ExpressionEngineLexer缓存机制,进一步提升性能 Jan 20, 2019
ExpressionEngineLexerMapCache.go fix Apr 13, 2019
ExpressionEngineLexerMapCache_test.go 新增 ExpressionEngineLexer缓存机制,进一步提升性能 Jan 20, 2019
ExpressionEngineProxy.go fix Apr 13, 2019
ExpressionEngineProxy_test.go fix Apr 13, 2019
GoMybatis.go 修改默认参数逻辑,默认参数为arg0,arg1.... Jun 21, 2019
GoMybatisConst.go 修改默认参数逻辑,默认参数为arg0,arg1.... Jun 21, 2019
GoMybatisDataSourceRouter.go 事务传播行为改为默认单协程模型(因为go标准库的http模块,基于标准库的http框架例如beego等handle都属于同一线程处理的)用… Apr 28, 2019
GoMybatisEnableType.go fix bug Dec 10, 2018
GoMybatisEngine.go edit log system May 3, 2019
GoMybatisEngine_test.go 回滚 May 18, 2019
GoMybatisProxy.go proxy 深层代理 May 11, 2019
GoMybatisProxy_test.go rename method Apr 20, 2019
GoMybatisReturnType.go 修改mapper方法定义结构,更加直观 Dec 9, 2018
GoMybatisRowsDecoder.go 回滚 May 18, 2019
GoMybatisSqlArgTypeConvert.go fix ptr convert May 27, 2019
GoMybatisSqlArgTypeConvert_test.go fix bug May 19, 2019
GoMybatisSqlBuilder.go edit log system May 3, 2019
GoMybatisSqlBuilder_test.go fix Apr 13, 2019
GoMybatisSqlResultDecoder.go clean code May 27, 2019
GoMybatisSqlResultDecoder_test.go 回滚 May 18, 2019
GoMybatisTempleteDecoder.go fix bug GoMybatisTempleteDecoder.DecodeWheres() append add Jul 6, 2019
GoMybatisTempleteDecoder_test.go 回滚 May 18, 2019
GoroutineSessionMap.go fix 使用线程安全的map Apr 24, 2019
LICENSE 符合golint 规范,使用it代替this 作为接收器 Jan 26, 2019
LocalSession.go 回滚 May 18, 2019
Log.go format project Jan 26, 2019
LogStandard.go 符合golint 规范,使用it代替this 作为接收器 Jan 26, 2019
LogStandard_test.go 添加测试 Jan 21, 2019
LogSystem.go fix Apr 13, 2019
LogSystem_test.go 开放日志消息队列,开放日志实现接口参数 Jan 26, 2019
ProxyArg.go add callback chan Apr 18, 2019
README-ch.md add english readme Aug 16, 2019
README.md Update README.md Aug 16, 2019
ResultMap.go 完成ResultMap支持 Nov 30, 2018
SessionFactory.go 事务传播行为,未添加注解的方法加入上一个事务 May 12, 2019
SessionFactorySession.go 回滚 May 18, 2019
SessionSupport.go 新增session 隐式实现 Apr 13, 2019
SessionType.go 删除远程事务功能.后期采用其他的实现方式 Apr 13, 2019
SqlBuilder.go edit log system May 3, 2019
SqlEngine.go 回滚 May 18, 2019
SqlResultDecoder.go 回滚 May 18, 2019
TempleteDecoder.go fix Apr 13, 2019
TransactionAspectSupport.go 事务传播行为,未添加注解的方法加入上一个事务 May 12, 2019
XmlCreate.go fix bug May 5, 2019
XmlCreate_test.go add xml create util May 5, 2019
XmlLoader.go fix Apr 13, 2019
XmlLoader_test.go 清理数据 Mar 3, 2019
mybatis-3-mapper.dtd dtd fix May 5, 2019
type.go format project Dec 29, 2018

README.md

SQL mapper ORM framework for Golang

Go Report Card Build Status GoDoc Coverage Status codecov

Image text

Please read the documentation website carefully when using the tutorial. DOC

Features

  • High Performance,The maximum number of transactions per second of a single computer can reach 456621Tps/s, and the total time consumed is 0.22s (test environment returns simulated SQL data, concurrently 1000, total 100000, 6-core 16GB win10)
  • Painless migration from Java to go,Compatible with most Java(Mybatis3,Mybatis Plus) ,Painless migration of XML SQL files from Java Spring Mybatis to Go language(Modify only the javaType of resultMap to specify go language type for langType)
  • Declarative transaction/AOP transaction/transaction BehaviorOnly one line Tag is needed to define AOP transactions and transaction propagation behavior
  • Extensible Log InterfaceAsynchronous message queue day, SQL log in framework uses cached channel to realize asynchronous message queue logging
  • dynamic sql,contains 15 utilities Features<select>,<update>,<insert>,<delete>,<trim>,<if>,<set>,<where>,<foreach>,<resultMap>,<bind>,<choose><when><otherwise>,<sql><include>
  • Intelligent expressionProcessing dynamic judgment and computation tasks(such as:#{foo.Bar}#{arg+1}#{arg*1}#{arg/1}#{arg-1}),For example, write fuzzy queries select * from table where phone like #{phone+'%'}(Note the post-percentile query run in index)
  • Dynamic Data SourceMultiple data sources can be customized to dynamically switch multiple database instances
  • Template label(new)One line of code to achieve add, delete, modify, delete logic, optimistic lock, but also retain perfect scalability (tag body can continue to expand SQL logic)
  • Optimistic Lock(new)<updateTemplete>Optimistic locks to prevent concurrent competition to modify records as much as possible
  • Logical deletion(new)<insertTemplete><updateTemplete><deleteTemplete><selectTemplete>Logical deletion, prevent accidental deletion of data, data recovery is simple
  • RPC/MVC Component Support(new)To make the service perfect for RPC (reducing parameter restrictions), dynamic proxy, transaction subscription, easy integration and extension of micro services, click on the link https://github.com/zhuxiujia/easyrpc

Database Driver support table

 //Traditional database
 Mysql:                             github.com/go-sql-driver/mysql
 MyMysql:                           github.com/ziutek/mymysql/godrv
 Postgres:                          github.com/lib/pq
 SQLite:                            github.com/mattn/go-sqlite3
 MsSql:                             github.com/denisenkom/go-mssqldb
 MsSql:                             github.com/lunny/godbc
 Oracle:                            github.com/mattn/go-oci8
 //Distributed NewSql database
 Tidb:                              github.com/pingcap/tidb
 CockroachDB:                       github.com/lib/pq

Use tutorials

Tutorial source code https://github.com/zhuxiujia/GoMybatis/tree/master/example

Set up GoPath and download GoMybatis and the corresponding database driver with the go get command

go get github.com/zhuxiujia/GoMybatis
go get github.com/go-sql-driver/mysql

In practice, we use mapper to define the content of xml. It is suggested that the * Mapper. XML file be stored in the project directory. When editing xml, we can enjoy IDE rendering and intelligent prompts such as GoLand. Production environments can use statikFS to package XML files in the process

  • main.go
var xmlBytes = []byte(`
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://raw.githubusercontent.com/zhuxiujia/GoMybatis/master/mybatis-3-mapper.dtd">
<mapper>
    <select id="SelectAll">
        select * from biz_activity where delete_flag=1 order by create_time desc
    </select>
</mapper>
`)
import (
	"fmt"
	_ "github.com/go-sql-driver/mysql" //Select the required database-driven imports
	"github.com/zhuxiujia/GoMybatis"
)
type ExampleActivityMapperImpl struct {
     SelectAll  func() ([]Activity, error)
}

func main() {
    var engine = GoMybatis.GoMybatisEngine{}.New()
	//Mysql link format user name: password @ (database link address: port)/database name, such as root: 123456 @(***.com: 3306)/test
	err := engine.Open("mysql", "*?charset=utf8&parseTime=True&loc=Local")
	if err != nil {
	   panic(err)
	}
	var exampleActivityMapperImpl ExampleActivityMapperImpl
	
	//Loading XML implementation logic to ExampleActivity Mapper Impl
	engine.WriteMapperPtr(&exampleActivityMapperImpl, xmlBytes)

	//use mapper
	result, err := exampleActivityMapperImpl.SelectAll(&result)
        if err != nil {
	   panic(err)
	}
	fmt.Println(result)
}

Features: Template tag CRUD simplification (must rely on a resultMap tag)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://raw.githubusercontent.com/zhuxiujia/GoMybatis/master/mybatis-3-mapper.dtd">
<mapper>
    <!--logic_enable Logical Delete Fields-->
    <!--logic_deleted Logically delete deleted fields-->
    <!--logic_undelete Logically Delete Undeleted Fields-->
    <!--version_enable Optimistic lock version field, support int, int8, int16, int32, Int64-->
    <resultMap id="BaseResultMap" tables="biz_activity">
        <id column="id" property="id"/>
        <result column="name" property="name" langType="string"/>
        <result column="pc_link" property="pcLink" langType="string"/>
        <result column="h5_link" property="h5Link" langType="string"/>
        <result column="remark" property="remark" langType="string"/>
        <result column="version" property="version" langType="int"
                version_enable="true"/>
        <result column="create_time" property="createTime" langType="time.Time"/>
        <result column="delete_flag" property="deleteFlag" langType="int"
                logic_enable="true"
                logic_undelete="1"
                logic_deleted="0"/>
    </resultMap>
    <!--Template tags: columns wheres sets support commas, separating expressions, *?* as null expressions-->
    <!--Insert Template: Default id="insertTemplete,test="field != null",where Automatically set logical deletion fields to support batch insertion" -->
    <insertTemplete/>
    <!--Query template: default id="selectTemplete,where Automatically Set Logical Delete Fields-->
    <selectTemplete wheres="name?name = #{name}"/>
    <!-- Update template: default id="updateTemplete,set Automatically Setting Optimistic Lock Version Number-->
    <updateTemplete sets="name?name = #{name},remark?remark=#{remark}" wheres="id?id = #{id}"/>
    <!--Delete template: default id="deleteTemplete,where Automatically Set Logical Delete Fields-->
    <deleteTemplete wheres="name?name = #{name}"/>
</mapper>    

XML corresponds to the Mapper structure method defined below

type Activity struct {
	Id         string    `json:"id"`
	Uuid       string    `json:"uuid"`
	Name       string    `json:"name"`
	PcLink     string    `json:"pcLink"`
	H5Link     string    `json:"h5Link"`
	Remark     string    `json:"remark"`
	Version    int       `json:"version"`
	CreateTime time.Time `json:"createTime"`
	DeleteFlag int       `json:"deleteFlag"`
}
type ExampleActivityMapper struct {
	SelectTemplete      func(name string) ([]Activity, error) `mapperParams:"name"`
	InsertTemplete      func(arg Activity) (int64, error)
	InsertTempleteBatch func(args []Activity) (int64, error) `mapperParams:"args"`
	UpdateTemplete      func(arg Activity) (int64, error)    `mapperParams:"name"`
	DeleteTemplete      func(name string) (int64, error)     `mapperParams:"name"`
}

Features:Dynamic Data Source

        //To add a second MySQL database, change Mysql Uri to your second data source link
	GoMybatis.Open("mysql", MysqlUri)
	//Dynamic Data Source Routing
	var router = GoMybatis.GoMybatisDataSourceRouter{}.New(func(mapperName string) *string {
		//Point to the data source according to the packet name routing
		if strings.Contains(mapperName, "example.") {
			var url = MysqlUri//The second MySQL database, please change Mysql Uri to your second data source link
			fmt.Println(url)
			return &url
		}
		return nil
	})

Features:Custom log output

	engine.SetLogEnable(true)
	engine.SetLog(&GoMybatis.LogStandard{
		PrintlnFunc: func(messages []byte) {
		  //do someting save messages
		},
	})

Features:Asynchronous log interface (customizable log output)

Image text

Features:Transaction Propagation Processor (Nested Transactions)

Transaction type Explain
PROPAGATION_REQUIREDRepresents that if the current transaction exists, the current transaction is supported. Otherwise, a new transaction will be started. Default transaction type.
PROPAGATION_SUPPORTSRepresents that if the current transaction exists, the current transaction is supported, and if there is no transaction at present, it is executed in a non-transactional manner.
PROPAGATION_MANDATORYRepresents that if the current transaction exists, the current transaction is supported, and if no transaction exists, the transaction nesting error is returned.
PROPAGATION_REQUIRES_NEWRepresents that a new Session opens a new transaction and suspends the current transaction if it currently exists.
PROPAGATION_NOT_SUPPORTEDRepresents that an operation is performed in a non-transactional manner. If a transaction exists, a new Session is created to perform the operation in a non-transactional manner, suspending the current transaction.
PROPAGATION_NEVERRepresents that an operation is executed in a non-transactional manner and returns a transaction nesting error if a transaction currently exists.
PROPAGATION_NESTEDRepresents that if the current transaction exists, it will be executed within the nested transaction. If the nested transaction rolls back, it will only roll back within the nested transaction and will not affect the current transaction. If there is no transaction at the moment, do something similar to PROPAGATION_REQUIRED.
PROPAGATION_NOT_REQUIREDRepresents that if there is currently no transaction, a new transaction will be created, otherwise an error will be returned.
//Nested transaction services
type TestService struct {
   exampleActivityMapper *ExampleActivityMapper //The service contains a mapper operation database similar to Java spring MVC
   UpdateName   func(id string, name string) error   `tx:"" rollback:"error"`
   UpdateRemark func(id string, remark string) error `tx:"" rollback:"error"`
}
func main()  {
   var testService TestService
   testService = TestService{
   	exampleActivityMapper: &exampleActivityMapper,
   	UpdateRemark: func(id string, remark string) error {
   		testService.exampleActivityMapper.SelectByIds([]string{id})
   		panic(errors.New("Business exceptions")) // panic Triggered transaction rollback strategy
   		return nil                   // rollback:"error" A transaction rollback policy is triggered if the error type is returned and is not nil
   	},
   	UpdateName: func(id string, name string) error {
   		testService.exampleActivityMapper.SelectByIds([]string{id})
   		return nil
   	},
   }
   GoMybatis.AopProxyService(&testService, &engine)//Func must use AOP proxy service
   testService.UpdateRemark("1","remark")
}

Features:XML/Mapper Generator - Generate * mapper. XML from struct structure

  //step1 To define your database model, you must include JSON annotations (default database fields), gm:"" annotations specifying whether the value is id, version optimistic locks, and logic logic soft deletion.
  type UserAddress struct {
	Id            string `json:"id" gm:"id"`
	UserId        string `json:"user_id"`
	RealName      string `json:"real_name"`
	Phone         string `json:"phone"`
	AddressDetail string `json:"address_detail"`

	Version    int       `json:"version" gm:"version"`
	CreateTime time.Time `json:"create_time"`
	DeleteFlag int       `json:"delete_flag" gm:"logic"`
}
  • Step 2: Create an Xml CreateTool. go in the main directory of your project as follows
func main() {
	var bean = UserAddress{} //Here's just an example, which should be replaced by your own database model
	GoMybatis.OutPutXml(reflect.TypeOf(bean).Name()+"Mapper.xml", GoMybatis.CreateXml("biz_"+GoMybatis.StructToSnakeString(bean), bean))
}
  • Third, execute the command to get the UserAddressMapper. XML file in the current directory
go run XmlCreateTool.go
  • The following is the content of the automatically generated XML file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://raw.githubusercontent.com/zhuxiujia/GoMybatis/master/mybatis-3-mapper.dtd">
<mapper>
    <!--logic_enable Logical Delete Fields-->
    <!--logic_deleted Logically delete deleted fields-->
    <!--logic_undelete Logically Delete Undeleted Fields-->
    <!--version_enable Optimistic lock version field, support int, int8, int16, int32, Int64-->
    <resultMap id="BaseResultMap" tables="biz_user_address">
    <id column="id" property="id"/>
	<result column="id" property="id" langType="string"   />
	<result column="user_id" property="user_id" langType="string"   />
	<result column="real_name" property="real_name" langType="string"   />
	<result column="phone" property="phone" langType="string"   />
	<result column="address_detail" property="address_detail" langType="string"   />
	<result column="version" property="version" langType="int" version_enable="true"  />
	<result column="create_time" property="create_time" langType="Time"   />
	<result column="delete_flag" property="delete_flag" langType="int"  logic_enable="true" logic_undelete="1" logic_deleted="0" />
    </resultMap>
</mapper>

Components (RPC, JSONRPC, Consul) - With GoMybatis

Please pay attention to the version in time, upgrade the version in time (new features, bug fix). For projects using GoMybatis, please leave your project name + contact information in Issues.

Welcome to Star or Wechat Payment Sponsorship at the top right corner~

Image text

You can’t perform that action at this time.