Mybatis進行id型別、String型別、map型別、ben型別引數傳入Sql查詢
阿新 • • 發佈:2019-02-01
用習慣了Hibernate,再換成Mybatis總會遇到一些變態問題,正如下面的錯誤提示,用mybatis查詢時,傳入一個字串傳引數,且進行判斷時,會報 錯誤
There is no getter for property named 'moduleCode' in 'class java.lang.String
Dao層呼叫方式
常見的錯誤寫法:XML對映Sql/* * Dao層查詢 */ @Override public List<CityFace> findCityFaceByCondition(String eqDate) { return sqlSession.selectList(CityFace.class.getName()+"_Mapper.findCityFaceByCondition",eqDate); }
需要修改成:<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>
不管你的引數是什麼,都要改成"_parameter",但是ID就不用改就行<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>
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>