5

golang sql mapper framework

 1 year ago
source link: https://studygolang.com/articles/36168
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Juice 简介

juice 是一个基于 golang 的 sql mapper 框架,它的目标是提供一个简单易用的 sql mapper 框架,让开发者可以更专注于业务逻辑的开发。

如果你是一个 golang 开发者,或者你正在寻找一个简单易用的 sql mapper 框架,那么 juice 可能是你的不二之选。

http://github.com/eatmoreapple/juice

  • 轻量级,高性能,无第三方依赖
  • 简单易用,容易扩展
  • 动态 sql 语句
  • 支持多数据源
  • 泛型结果集映射
  • 自定义表达式
  • 自定义函数

版本要求

  • go 1.18+
go get -u github.com/eatmoreapple/juice

快速开始 编写sql mapper配置文件

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <environments default="prod">
        <environment id="prod">
            <dataSource>root:qwe123@tcp(localhost:3306)/database</dataSource>
            <driver>mysql</driver>
        </environment>
    </environments>

    <mappers>
        <mapper namespace="main">
            <select id="HelloWorld">
                select "hello world" as message
            </select>
        </mapper>
    </mappers>
</configuration>

注意:dataSource 的格式跟用 sql.Open() 函数的格式相同。

package main

import (
   "fmt"
   "github.com/eatmoreapple/juice"
   _ "github.com/go-sql-driver/mysql"
)

func HelloWorld() {}

func main() {
   cfg, err := juice.NewXMLConfiguration("config.xml")
   if err != nil {
      fmt.Println(err)
      return
   }

   engine, err := juice.DefaultEngine(cfg)
   if err != nil {
      fmt.Println(err)
      return
   }
   message, err := juice.NewGenericManager[string](engine).Object(HelloWorld).Query(nil)
   if err != nil {
      fmt.Println(err)
      return
   }
   fmt.Println(message)
}

注意:虽然 juice 不依赖第三方库,但是它需要依赖数据库驱动,所以在使用 juice 之前,你需要先安装数据库驱动,比如要使用mysql, 那么你需要先安装 github.com/go-sql-driver/mysql

如果运行报错,那么可能是因为你的数据库没有启动,或者你的数据库配置有误,检查一下数据库配置是否正确。

go run main.go
[juice] 2022/11/05 19:56:49 [main.HelloWorld]  select "hello world" as message  []  5.3138ms
hello world

文档地址:https://juice-doc.readthedocs.io/en/latest/index.html


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK