目的:利用mybatis动态生成sql的能力返回可执行的sql,但并不会执行。
场景:需要生成复杂的sql供其他程序执行
- 编写xml: SqlGenarate.mapper.xml
<?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="com.jason.bi.data.sql.generate">
<select id="getSql">
SELECT
a,
b
FROM
`table_name`
WHERE
field1 = #{field1Value} AND field2 = #{field2Value}
</select>
</mapper>
- 定义接口
import io.swagger.annotations.ApiOperation;
import java.util.Map;
/**
* @author: jason
* @Date: 2022-01-04
*/
public interface SqlService {
@ApiOperation(value = "动态生成sql")
String generate(String sqlId, Map<String, Object> paramMap);
}
- 实现接口
sqlId = namespace + ‘.’ + id
如SqlGenarate.mapper.xml中getSql对应的sqlId即为:com.jason.bi.data.sql.generate.getSql
paramMap为参数,paramMap.put(“field1Value”,“abc”),paramMap.put(“field2Value”,“efg”),
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author: jason
* @Date: 2022-01-04
*/
@Service
public class SqlServiceImpl implements SqlService {
@Autowired
private SqlSessionFactory sqlSessionFactory;
@Override
public String generate(String sqlId, Map<String, Object> paramMap) {
//获取执行sql
Configuration con = sqlSessionFactory.getConfiguration();
//传xml文件中的 需要执行的id编号,如: com.jason.bi.data.sql.generate.getSql
MappedStatement s = con.getMappedStatement(sqlId);
BoundSql bSql = s.getBoundSql(paramMap);
//获取到sql中封装的参数的数量
List<ParameterMapping> paramValues = bSql.getParameterMappings();
return getExecuteSql(bSql.getSql(), paramValues, paramMap);
}
/**
* 生成可执行sql
*
* @param sql 获取的sql
* @param paramValues 动态参key
* @param map 动态参valur
* @return
*/
private String getExecuteSql(String sql, List<ParameterMapping> paramValues, Map map) {
while (sql.indexOf("?") != -1 && paramValues.size() > 0) {
String paramName = paramValues.get(0).getProperty();
String paramValue = map.get(paramName).toString();
String value = "";
if (paramValue instanceof String) {
value = "'" + paramValue + "'";
}
sql = sql.replaceFirst("\\?", value);
paramValues.remove(0);
}
return sql;
}
}