檢視原文:http://www.ibloger.net/article/285.html
用習慣了Hibernate,再換成Mybatis總會遇到一些變态問題,正如下面的錯誤提示,用mybatis查詢時,傳入一個字元串傳參數,且進行判斷時,會報 錯誤
There is no getter for property named 'moduleCode' in 'class java.lang.String
Dao層調用方式
/*
* Dao層查詢
*/
@Override
public List<CityFace> findCityFaceByCondition(String eqDate) {
return sqlSession.selectList(CityFace.class.getName()+"_Mapper.findCityFaceByCondition",eqDate);
}
常見的錯誤寫法:XML映射Sql
<select id="findCityFaceByCondition" parameterType="String" resultType="CityFace">
select * from (select unitname, to_char(rdate,'yyyy-MM') rdate,analysistype, scope from CITYSCAPEANALYSIS)
pivot (sum(scope) for analysistype in ('ESScope' esscope, 'EOScope' eoscope,'GCScope' gcscope, 'CScope' cscope))
<if test='eqDate!=""'>
where rdate = #{eqDate}
</if>
</select>
需要修改成:
<select id="findCityFaceByCondition" parameterType="String" resultType="CityFace">
select * from (select unitname, to_char(rdate,'yyyy-MM') rdate,analysistype, scope from CITYSCAPEANALYSIS)
pivot (sum(scope) for analysistype in ('ESScope' esscope, 'EOScope' eoscope,'GCScope' gcscope, 'CScope' cscope))
<if test='_parameter!=""'>
where rdate = #{_parameter}
</if>
</select>
不管你的參數是什麼,都要改成"_parameter",但是ID就不用改就行
Java調用ID示例
@Override
public Visitlogs findVisitlogsById(int id) {
return sqlSession.selectOne(Visitlogs.class.getName()+"_Mapper.findVisitlogsById", id);
}
xml映射
<!-- 根據id查詢使用者 -->
<select id="findVisitlogsById" parameterType="int" resultMap="resultVisitlogs">
select * from visitlogs where id=#{id}
</select>
———————————————————————————分割線————————————————————————————
上面說的是String單個值,如果是多個值就可以使用map對象和Bean類對象進行封裝,然後就可以使用常用的方式接收了,比如下面的案例
Java調用Map示例
@Override
public AppUser loginUser(String userName, String password) {
Map<String, String> map = new HashMap<String, String>();
map.put("name", userName);
map.put("password", password);
return sqlSession.selectOne(AppUser.class.getName()+"_Mapper.loginUser", map);
}
xml映射
<!-- 登入使用者 -->
<select id="loginUser" parameterType="map" resultType="AppUser">
select * from app_user where name=#{name} and password=#{password}
</select>
Java調用Bean類示例
@Override
public AppUser loginUser(String userName, String password) {
AppUser user = new AppUser();
user.setName(userName);
user.setPassword(password);
return sqlSession.selectOne(AppUser.class.getName()+"_Mapper.loginUser", user);
}
xml映射
<!-- 登入使用者 -->
<select id="loginUser" parameterType="AppUser" resultType="AppUser">
select * from app_user where name=#{name} and password=#{password}
</select>