ibatis使用中遇到sql语句中有$和#的处理方法

最近搞oracle text的全文检索功能,发现在项目中使用ibatis在查询ctxsys.dr$class这个表时,总是报错,错误如下

 com.ibatis.common.jdbc.exception.NestedSQLException:   
--- The error occurred in com/tc/fts/ibatis/map/CTXSYS_DRCLASS_SqlMap.xml.  
--- The error occurred while preparing the mapped statement for execution.  
--- Check the selectDrClass.  
--- Check the SQL statement.  
--- Cause: java.util.NoSuchElementException
	at com.ibatis.sqlmap.engine.mapping.statement.GeneralStatement.executeQueryWithCallback(GeneralStatement.java:188)
	at com.ibatis.sqlmap.engine.mapping.statement.GeneralStatement.executeQueryForList(GeneralStatement.java:123)
	at com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate.queryForList(SqlMapExecutorDelegate.java:615)
	at com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate.queryForList(SqlMapExecutorDelegate.java:589)

 后来才发现表名中含有美元符,而在sqlmap中$是用来替换变量的,是sqlmap中特殊意义的字符,所以直接这么写到sql中肯定是不行的了。

可以考虑使用变量传值的方式,将表名当参数传进来。做了如下更改

调用代码:

ls = sqlMap.queryForList("selectDrClass","ctxsys.dr$class");

 sqlmap代码:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd" >
<sqlMap namespace="CTXSYS_DRCLASS" >
  <select id="selectDrClass" resultClass="com.tc.fts.ibatis.model.DrClass" parameterClass="java.lang.String" >
  <![CDATA[
    select * from #temp# order by CLA_ID
    ]]>
  </select>
</sqlMap>

 结果发现ibatis默认将select * from #temp# order by CLA_ID变成了sql语句的参数化形式select * from ? order by CLA_ID,然后调用setString(1)了,这样最后的sql语句中表名被加了引号了。所以还是不行。

 

尝试直接代换法,这次OK了

调用代码:

dc.setClaName("ctxsys.dr$class");
ls = sqlMap.queryForList("selectDrClass",dc);

 sqlmap代码:

<select id="selectDrClass" resultClass="com.tc.fts.ibatis.model.DrClass" parameterClass="com.tc.fts.ibatis.model.DrClass" >
  <![CDATA[
    select * from $claName$ order by CLA_ID
    ]]>
  </select>

 这样执行的时候sql语句就被正常代换成

select * from ctxsys.dr$class order by CLA_ID

 

 现在又发现一种方法可以这样更符合要求,原谅我之前的做法吧

ls = sqlMap.queryForList("selectDrClass","ctxsys.dr$class");

 

	<select id="selectDrClass"
		resultClass="com.tc.fts.ibatis.model.DrClass"
		parameterClass="String">
		<![CDATA[
    select cla_Id claid,cla_Name claname,cla_Desc cladesc from $value$ order by CLA_ID
    ]]>
	</select>

 

 

你可能感兴趣的:(apache,oracle,sql,ibatis,全文检索)