15_动态SQL

【UserMapper.xml】和之前的作对比

<mapper namespace="com.Higgin.Mybatis.mapper.UserMapper">
 
     <!--
          用户信息的综合查询(复杂查询)
         #{userCustom.sex}:取出pojo包装对象中的"性别"值
         #{userCusotm.username}:取出pojo包装类中用户名称
      -->
     <select id="findUserList" parameterType="com.Higgin.Mybatis.po.UserQueryVo"
                               resultType="com.Higgin.Mybatis.po.UserCustom">
         SELECT * FROM USER WHERE user.sex =#{userCustom.sex} AND user.username LIKE '%${userCustom.username}%'
     </select>
     
     <!--
          用户信息的综合查询(复杂查询)
          使用动态SQL的方式
      -->
     <select id="findUserList2" parameterType="com.Higgin.Mybatis.po.UserQueryVo"
                               resultType="com.Higgin.Mybatis.po.UserCustom">
         SELECT * FROM USER
          <where>
              <if test="userCustom!=null">
                  <if test="userCustom.sex!=null and userCustom.sex!=''">
                      and user.sex=#{userCustom.sex}
                  </if>
                  <if test="userCustom.username!=null and userCustom.username!=''">
                      and user.username LIKE '%${userCustom.username}%'
                  </if>
              </if>
          </where>
     </select>

</mapper>

 

【UserMapper.java】接口

public interface UserMapper {
    
    //用户信息综合查询findUserList
    public List<UserCustom> findUserList(UserQueryVo userQueryVo) throws Exception;//动态SQL:用户信息综合查询findUserList2
    public List<UserCustom> findUserList2(UserQueryVo userQueryVo) throws Exception;
}

 

【UserMapperTest.java】测试

/** 
     * 用户信息的综合查询
     * @throws Exception
     */
    @Test
    public void testFindUserList2() throws Exception {
        
        SqlSession sqlSession =sqlSessionFactory.openSession();
         
        //创建一个UserMapper对象,Mybatis自动生成mapper代理对象
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        
        //创建包装对象,设置查询条件
        UserQueryVo userQueryVo=new UserQueryVo();
        UserCustom userCustom=new UserCustom();
        
        userCustom.setSex("1");
        userCustom.setUsername("6");   //这两句分别被注释,将会忽略被注释的条件进行查询
        
        userQueryVo.setUserCustom(userCustom);
        
        //调用UserMapper的方法
        List<UserCustom> list=userMapper.findUserList2(userCustom);   //传入的参数为null时,不会进行查询,且不会报错!!!之前的方式传入参数为null会报错

            System.out.println(list.size());
    }

 

posted @ 2016-08-12 00:24  HigginCui  阅读(321)  评论(0编辑  收藏  举报