SpringBoot+MyBatis实现动态(Sql存在表中)获取Sql

在前端传参中携带SQLID,例如:

 this.bidm.request('get-result-by-sql-Key', {SQLID:'test', USERACCOUNT:'10047396'}).then(
      function (res) {
      console.log(res);  
    });

在Controler中通过SqlID获取Sql表中的Sql语句

@BidmMethod(name = "get-result-by-sql-Key")
public BidmResponse getResultBySqlKey(BidmRequest request) throws Exception
{	
        //request包含sqlid和sql中需要的参数
	String sqlId = BidmUtils.getRequestParam(request, "SQLID");
	Map<String, Object> map=new HashMap<>();
	map=request.getParams();
	map.remove("SQLID");
	BidmResponse response = new BidmResponse();
	BidmSQL sql = this.bidmService.getSqlByKey(sqlId);
	//以上通过Mapper传统方式获取sql语句,以下通过SelectProvider动态组建Sql语句
	List<Map<String,Object>> resultMap=queryService.getQueryResult(sql.getSql(), map);
	if(resultMap.size()>0) {
		response.setErrorCode(ErrorCode.BIDM_SUCCESS);
		response.addParam("list", JsonUtils.toJsonList(resultMap));
	}
	else {
		response.setErrorCode(ErrorCode.BIDM_ITEM_NOT_EXISTS);
	}
	return response;
}

Service与Impl无需变更

Mapper.java:

package com.boe.bidm.project.mapper;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.SelectProvider;
import com.boe.bidm.project.selectProvider.SqlProviderUtil;

@Mapper
public interface CommonQueryMapper {

	@SelectProvider(type = SqlProviderUtil.class, method = "commonQuery")
        //注解需声明SqlProviderUtil和方法名,执行返回查询结果
	List<Map<String, Object>> getQueryResult(String sql,Map<String, Object> map) throws Exception;
	
}

SqlProviderUtil工具类

package com.boe.bidm.project.selectProvider;

import java.util.Map;
import java.util.Map.Entry;

public class SqlProviderUtil {
	public String commonQuery(String sql,Map<String, Object> map) 
	{
                //替换Sql语句中的变量
		if(sql.indexOf(":")!=-1)
		{
			for(Entry<String, Object> vo : map.entrySet())
			{
				sql=sql.replaceAll(":"+vo.getKey(), "'"+vo.getValue().toString()+"'");
			}
		}
		else
		{
			
		}
		System.out.println("SQL Content:"+sql);
		return sql;
	}
}

以上,便可通过查询表中的sql,替换 变量后即可实现sql查询,这样的好处是如果sql需要变更,且参数不增加,就可只改sql,而不需要发布系统

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值