达梦类型为json字符串的处理

返回
Author Avatar
钢翼
2020-12-31
编程
55

mysql支持json数据类型的字段。达梦只能用text类型来代替
mysql查询json字段的语法如下

select * from table1 where col1->'$.filed1' = 123 

达梦查询语法要变成

select * from table1 where json_value(col1,'$.filed1')= 123

为了一套代码兼容两套数据库,我们可以只写一套mysql的语法,然后如果检测到数据源是达梦,则对查询条件进行正则匹配,并替换。

//conditionSql格式为"col1->'$.filed1' = 123"
//转换后格式为"json_value(col1,'$.filed1')= 123"
private String convert(conditionSql){
	String str = conditionSql;
	if(!StringUtils.isEmpty(conditionSql)) {
        Pattern reg = Pattern.compile("(.*?)->('.*?')(.*)");
        Matcher matcher = reg.matcher(conditionSql);
        if(matcher.find()){
          str = "json_value("+matcher.group(1)+","+matcher.group(2)+")"+matcher.group(3);
        }
    }
  return str;
}