我想从我的Java源代码中解析我的SQL查询。查询属于所有类型,包括各种引号和换行符。它们通常被分配给源中的变量,如:
String query = "Select a from b..."
是否有人知道从Java代码解析SQL查询的框架?
答案 0 :(得分:0)
我的Batis字符串替换
默认情况下,使用#{}语法将导致MyBatis生成PreparedStatement属性,并根据PreparedStatement参数(例如?)安全地设置值。虽然这更安全,更快速且几乎总是首选,但有时您只想将未修改的字符串直接注入SQL语句。例如,对于ORDER BY,您可以使用以下内容:
ORDER BY ${columnName}
服务层
@Service
public class RuleService{
@Autowired
private RuleDAOMapper ruleDAOMapper;
@Transactional
public List<Map<String,Object>> selectAll() throws Exception{
Map<String,Object> paramSpecialRules=new HashMap<String,Object>();
paramSpecialRules.put("query", "Select a from b where id=#{id,jdbcType=VARCHAR}");
paramSpecialRules.put("id", 1506);
List<Map<String,Object>> specialRules = new ArrayList<Map<String,Object>>();
try
{
specialRules = ruleDAOMapper.runQuery(paramSpecialRules);
}
catch (Exception e)
{
e.printStackTrace();
throw new Exception("ERROR IN READING");
}
}
}
DAO图层
@MapperScan
public interface RuleDAOMapper {
public List<Map<String,Object>> runQuery(Map param);
}
XML图层
<mapper namespace="com.codexamples.contact.dao.mybatis.mappers.RuleDAOMapper">
<select id="runQuery" parameterType="Map" resultType="java.util.LinkedHashMap" flushCache="true" useCache="false">
${query}
</select>
</mapper>
<强>参考:强>
http://www.mybatis.org/mybatis-3/sqlmap-xml.html 请参阅&#39;字符串替换&#39; MyBatis文档中的部分。
使用SQL列表
创建一个查询 StringBuilder query=new StringBuilder("select * from (");
for (Iterator<String> iterator2 = listOfSQLQueries.iterator(); iterator2.hasNext();) {//process exceptional SQL list on by one
String sqlUnit = (String) iterator2.next();
query.append(sqlUnit);
if(iterator2.hasNext())
query.append(" UNION ");
}
query.append(")");