dao層,增長SqlMapper.java和 對應的SQLMapper.xmljava
package rg.contacts.mapper; import java.util.LinkedHashMap; import java.util.List; import rg.contacts.vo.SqlVo; public interface SQLMapper { List<LinkedHashMap<String, Object>> selectBysql(SqlVo sqlVo); }
<?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="rg.contacts.mapper.SQLMapper"> <!-- ##### 萬能SQL原生映射 -zyh ##### --> <select id="selectBysql" parameterType="rg.contacts.vo.SqlVo" resultType="java.util.LinkedHashMap"> ${sql} </select> </mapper>
其中,使用 java.util.LinkedHashMap 做爲返回類型,能夠保持結果集原本的字段順序。sql
爲了不出現 :there no getter sql in java.lang.String 的異常,須要將sql分裝到SqlVo.javamybatis
package rg.contacts.vo; public class SqlVo { private String sql; public String getSql() { return sql; } public void setSql(String sql) { this.sql = sql; } }
若是不用sqlV封裝的話,能夠將mapper改成${value}:便可以不報錯,也能夠避免使用SqlVo.javaapp
<!-- ##### 萬能SQL原生映射 -zyh ##### --> <select id="selectBysql" parameterType="String" resultType="java.util.LinkedHashMap"> ${value} </select>
最後service的調用方式:ide
@Service public class GiftServiceImpl implements GiftService { @Autowired private SQLMapper sqlMapper; @Override public List<LinkedHashMap<String, Object>> selectBySQL(Integer sqlStr) { // TODO Auto-generated method stub SqlVo sqlVo = new SqlVo(); sqlVo.setSql(sqlStr); return sqlMapper.selectBysql(sqlVo); } }
爲了不出現值null的列,不能被保存到 LinkedHashMap對象 中,須要在mybatis 的配置文件中加以下配置:this
<settings> <!-- 調用setter null,返回空也必須設置到bean中 (直接執行sql專用)--> <setting name="callSettersOnNulls" value="true"/> </settings>
若是對您有幫助,請點贊spa