在java界鼎鼎大名的mybatis,现在已经有了相应的nodejs(14+)版:
es-batis,在github上开源,在npm库上更新。现在已经支持几乎所有的动态sql标签,并且这些标签可以任意嵌套使用
- insert
- select
- update
- delete
- sql
- where
- set
- trim
- if
- foreach
- bind
-
choose/when/otherwise
-
include
使用示例:
import sqlTemplate, {
AuroraEntity,
DBColumn,
initDaoContext,
MySqlDaoContext,
} from 'es-batis'
//更详细的参数请看参数类型申明,现在只支持非连接池的方式(因为用于serverless)
//more info for parameter,please refer to the source,only support none connection pool
const dao = new MySqlDaoContext({
charset: 'utf8',
host: 'mysqlhost',
user: 'user',
password: 'password',
})
await dao.initialize()
dao = initDaoContext({ dao })
const sql = sqlTemplate`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC
"-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper
namespace="esbatis.test">
<select id="selectOne" >
SELECT
t1.bank_name,
t1.id
FROM
bank AS t1
<where>
<if test="id != null">
and t1.id = #{id}
</if>
</where>
ORDER BY
t1.updated
</select>
</mapper>
`
let sqlResults = await sql.selectOne('esbatis.test.selectOne', { id: 1 })
//example returns:
//sqlResults = {
// bank_name: 'bank1',
// id: 1,
// }
并且在使用typescript(4.4.4)的前提下,还支持和单表ORM结合。
本库,进行了大量的测试,代码覆盖率,除了一些异常分支,基本做到了全覆盖,现在已经在内部项目中使用了,有兴趣的也可以尝试下。
创作本库的背景:
- 在nodejs界没有找到好用的和java一样的mybatis库,只有typeORM这些库,个人觉得不是很好用
- 可以让原来开发java的人员和顺利的使用他们熟悉的mybatis,减少迁移成本