前段时间设计一下动态sql解析的框架,主要是目标是将一些比较偏向于直接操作数据的业务整合到一个通用的框架中,以方便后续开发和维护。由于服务程序前期使用的是spring + mybatis的框架,sql都是通过mapper进行映射的,这种生成的mapper文件维护起来不方便,修改后需要编译后才能运行。另外一个原因是,业务需求变更比较频繁,所以在接口开发过程中花费了大量的精力。所以在考虑使用一种 sql模板的试,将sql语句事先定义在数据库,新增服务不需要编译只需要数据库添加几条记录就可以了。
Sql模板语句 :
select a.user_type, a.uname, a.full_name from t_um_user where a.user_type=${user_type,jdbcType=VARCAHR,required=true} AND b.full_name=${full_name,jdbcType=VARCHAR,required=true}
insert into t_um_user (phone, full_name) VALUES(${phone,jdbcType=VARCHAR},${full_name,jdbcType=VARCHAR});
update t_um_user set phone=${phone,jdbcType=VARCHAR}, full_name=${full_name,jdbcType=VARCHAR} where uid=${uid}
我们需要将上述语句解析成一个对象:
class BuildConfig {
Const{
fields
values
where
group
order
};
Variable{
fields
values
where
group
order
};
replaceholders{
name
placeholder
jdbcType
required
isArray
isVarchar
};
}
针对Insert 语句, 我们需要将 fields 和 values取出来
Pattern pattern = Pattern.compile("insert +into +(\\w+) *(?\\( *(\\w+)(? *, *(\\w+))*\\)) *VALUES *(?\\( *(\\w+)(? *, *(\\w+))* *\\))");
针对Select语句,我们需要将fields, where, group, order表达式取出来
Pattern pattern = Pattern.compile("select +(*\\w+ *(?, *(\\w+) *)*) +from +(\\w+) +(where +(?(\\w+) *= *(\\w+)))");