SkillAgentSearch skills...

GoMybatis

Go ORM Library.Have Powerful Features like transaction nesting, Optimistic Lock,Logical deletion and more. like mybatis for go golang

Install / Use

/learn @zhuxiujia/GoMybatis
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

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

Powerful Features

  • <a href="https://zhuxiujia.github.io/gomybatis.io/">High Performance</a>, 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)<br>
  • <a href="https://zhuxiujia.github.io/gomybatis.io/">Painless migration from Java to go</a>,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)<br>
  • <a href="https://zhuxiujia.github.io/gomybatis.io/">Declarative transaction/AOP transaction/transaction Behavior</a>Only one line Tag is needed to define AOP transactions and transaction propagation behavior<br>
  • <a href="https://zhuxiujia.github.io/gomybatis.io/">Extensible Log Interface</a>Asynchronous message queue day, SQL log in framework uses cached channel to realize asynchronous message queue logging<br>
  • <a href="https://zhuxiujia.github.io/gomybatis.io/">dynamic sql</a>,contains 15 utilities Features<select>,<update>,<insert>,<delete>,<trim>,<if>,<set>,<where>,<foreach>,<resultMap>,<bind>,<choose><when><otherwise>,<sql><include><br>
  • <a href="https://zhuxiujia.github.io/gomybatis.io/">Intelligent expression</a>Processing 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)<br>
  • <a href="https://zhuxiujia.github.io/gomybatis.io/">Dynamic Data Source</a>Multiple data sources can be customized to dynamically switch multiple database instances<br>
  • <a href="https://zhuxiujia.github.io/gomybatis.io/">Template label(new)</a>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)<br>
  • <a href="https://zhuxiujia.github.io/gomybatis.io/">Optimistic Lock(new)</a><updateTemplate>Optimistic locks to prevent concurrent competition to modify records as much as possible<br>
  • <a href="https://zhuxiujia.github.io/gomybatis.io/">Logical deletion(new)</a><insertTemplate><updateTemplate><deleteTemplate><selectTemplate>Logical deletion, prevent accidental deletion of data, data recovery is simple<br>
  • <a href="https://zhuxiujia.github.io/gomybatis.io/">RPC/MVC Component Support(new)</a>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<br>

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.9+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</br>

  • 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)

Image text

Features:Transaction Propagation Processor (Nested Transactions)

<table> <thead> <tr><th>Transaction type</th> <th>Explain</th> </tr> </thead> <tbody><tr><td>PROPAGATION_REQUIRED</td><td>Represents that if the current transaction exists, the current transaction is supported. Otherwise, a new transaction will be started. Default
View on GitHub
GitHub Stars446
CategoryDevelopment
Updated4d ago
Forks101

Languages

Go

Security Score

95/100

Audited on Mar 24, 2026

No findings