modulepackage
0.0.0-20211208044104-4e2ed600e4cf
Repository: https://github.com/fabletang/gomybatis2.git
Documentation: pkg.go.dev
# README
SQL mapper ORM framework for Golang
- English
- 中文
Please read the documentation website carefully when using the tutorial. DOC
Powerful Features
- High Performance, can reach 751020 Qps/s, and the total time consumed is 0.14s (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 queriesselect * 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)
<updateTemplate>
Optimistic locks to prevent concurrent competition to modify records as much as possible - Logical deletion(new)
<insertTemplate><updateTemplate><deleteTemplate><selectTemplate>
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(support all database of database/sql)
//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
Oracle: github.com/mattn/go-oci8
//Distributed NewSql database
Tidb: github.com/go-sql-driver/mysql
CockroachDB: github.com/lib/pq
Use tutorials
Tutorial source code https://github.com/zhuxiujia/GoMybatis/tree/master/example
- GoPath use, 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
- Go mod use
//go.mod加入依赖
require (
github.com/go-sql-driver/mysql v1.5.0
github.com/zhuxiujia/GoMybatis v6.5.6+incompatible
)
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 -->
<!--logic_deleted -->
<!--logic_undelete -->
<!--version_enable support int,int8,int16,int32,int64-->
<resultMap id="BaseResultMap" tables="biz_activity">
<id column="id" langType="string"/>
<result column="name" langType="string"/>
<result column="pc_link" langType="string"/>
<result column="h5_link" langType="string"/>
<result column="remark" langType="string"/>
<result column="sort" langType="int"/>
<result column="status" langType="status"/>
<result column="version" langType="int"
version_enable="true"/>
<result column="create_time" langType="time.Time"/>
<result column="delete_flag" langType="int"
logic_enable="true"
logic_undelete="1"
logic_deleted="0"/>
</resultMap>
<!--模板标签: columns wheres sets 支持逗号,分隔表达式,*?* 为判空表达式-->
<!--插入模板:默认id="insertTemplate,test="field != null",where自动设置逻辑删除字段,支持批量插入" -->
<insertTemplate/>
<!--查询模板:默认id="selectTemplate,where自动设置逻辑删除字段-->
<selectTemplate wheres="name?name = #{name}"/>
<!--更新模板:默认id="updateTemplate,set自动设置乐观锁版本号-->
<updateTemplate sets="name?name = #{name},remark?remark=#{remark}" wheres="id?id = #{id}"/>
<!--删除模板:默认id="deleteTemplate,where自动设置逻辑删除字段-->
<deleteTemplate 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 {
SelectTemplate func(name string) ([]Activity, error) `args:"name"`
InsertTemplate func(arg Activity) (int64, error)
InsertTemplateBatch func(args []Activity) (int64, error) `args:"args"`
UpdateTemplate func(arg Activity) (int64, error) `args:"name"`
DeleteTemplate func(name string) (int64, error) `args:"name"`
}
Features:Dynamic Data Source
//To add a second MySQL database, change Mysql Uri to your second data source link
var engine = GoMybatis.GoMybatisEngine{}.New()
engine.Open("mysql", MysqlUri)//添加第二个mysql数据库,请把MysqlUri改成你的第二个数据源链接
var router = GoMybatis.GoMybatisDataSourceRouter{}.New(func(mapperName string) *string {
//根据包名路由指向数据源
if strings.Contains(mapperName, "example.") {
var url = MysqlUri//第二个mysql数据库,请把MysqlUri改成你的第二个数据源链接
fmt.Println(url)
return &url
}
return nil
})
engine.SetDataSourceRouter(&router)
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)
Features:Transaction Propagation Processor (Nested Transactions)
Transaction type | Explain |
---|---|
PROPAGATION_REQUIRED | Represents that if the current transaction exists, the current transaction is supported. Otherwise, a new transaction will be started. Default transaction type. |
PROPAGATION_SUPPORTS | Represents 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_MANDATORY | Represents that if the current transaction exists, the current transaction is supported, and if no transaction exists, the transaction nesting error is returned. |
PROPAGATION_REQUIRES_NEW | Represents that a new Session opens a new transaction and suspends the current transaction if it currently exists. |
PROPAGATION_NOT_SUPPORTED | Represents 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_NEVER | Represents that an operation is executed in a non-transactional manner and returns a transaction nesting error if a transaction currently exists. |
PROPAGATION_NESTED | Represents 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_REQUIRED | Represents 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
- https://github.com/zhuxiujia/easy_mvc //mvc
- https://github.com/zhuxiujia/easyrpc //easyrpc
- https://github.com/zhuxiujia/easyrpc_discovery //easyrpc discovery
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~
# Packages
No description provided by the author
No description provided by the author
No description provided by the author
Package snowflake provides a very simple Twitter snowflake generator and parser.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
# Functions
使用AOP切面 代理目标服务,如果服务painc()它的事务会回滚默认为单协程模型,如果是多协程调用的情况请开启engine.SetGoroutineIDEnable(true).
使用AOP切面 代理目标服务,如果服务painc()它的事务会回滚.
*
//例子
//GoMybatis当前是以xml内容为主gm:""注解只是生成xml的时候使用
//定义数据库模型, gm:"id"表示输出id的xml,gm:"version"表示为输出版本号的xml,gm:"logic"表示输出逻辑删除xml
type TestActivity struct {
Id string `json:"id" gm:"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" gm:"version"`
CreateTime time.Time `json:"createTime"`
DeleteFlag int `json:"deleteFlag" gm:"logic"`
}
func TestUserAddres(t *testing.T) {
var s=utils.CreateDefaultXml("biz_user_address",TestActivity{})//创建xml内容
utils.OutPutXml("D:/GOPATH/src/dao/ActivityMapper.xml",[]byte(s))//写入磁盘
}
*/根据结构体 创建xml文件.注意 结构体json对应的是数据库的column.
No description provided by the author
输出文件.
AopProxy 可写入每个函数代理方法.proxyPtr:代理对象指针,buildFunc:构建代理函数.
AopProxy 可写入每个函数代理方法.
转蛇形命名snake string, XxYy to xx_yy , XxYY to xx_yy.
结构体名称转蛇形名称 例如 pcLink = pc_link.
写入方法内容,例如type ExampleActivityMapperImpl struct { SelectAll func(result *[]Activity) error SelectByCondition func(name string, startTime time.Time, endTime time.Time, page int, size int, result *[]Activity) error `args:"name,startTime,endTime,page,size"` UpdateById func(session *GoMybatis.Session, arg Activity, result *int64) error //只要参数中包含有*GoMybatis.Session的类型,框架默认使用传入的session对象,用于自定义事务 Insert func(arg Activity, result *int64) error CountByCondition func(name string, startTime time.Time, endTime time.Time, result *int) error `args:"name,startTime,endTime"`}func的基本类型的参数(例如string,int,time.Time,int64,float....)个数无限制(并且需要用Tag指定参数名逗号隔开,例如`args:"id,phone"`),返回值必须有errorfunc的结构体参数无需指定args的tag,框架会自动扫描它的属性,封装为map处理掉使用WriteMapper函数设置代理后即可正常使用。.
推荐默认使用单例传入根据sessionEngine写入到mapperPtr,value:指向mapper指针反射对象,xml:xml数据,sessionEngine:session引擎,enableLog:是否允许日志输出,log:日志实现.
推荐默认使用单例传入根据sessionEngine写入到mapperPtr,ptr:指向mapper指针,xml:xml数据,sessionEngine:session引擎,enableLog:是否允许日志输出,log:日志实现.
# Constants
No description provided by the author
默认参数前缀,例如arg0 arg1 arg2 ....
child elements.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
root template elements.
No description provided by the author
No description provided by the author
root elements.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
NewSession method,auto write implement body code.
默认session类型.
本地session.
# Variables
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
# Structs
No description provided by the author
No description provided by the author
动态数据源路由.
No description provided by the author
Sql内容类型转换器.
No description provided by the author
No description provided by the author
*
TODO sqlTemplate解析器,目前直接操作*etree.Element实现,后期应该改成操作xml,换取更好的维护性
*/.
No description provided by the author
本地直连session.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
代理数据.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
# Interfaces
数据源路由接口.
Lexer 结果缓存.
No description provided by the author
No description provided by the author
No description provided by the author
产生session的引擎.
sql文本构建.
sql查询结果解码.
No description provided by the author