zoukankan      html  css  js  c++  java
  • 17、mybatis学习——mybatis的动态sql之<choose><when><otherwise>选择唯一条件

    StudentMapper接口中定义方法

    StudentMapper配置文件进行相应的配置(这里没有写<otherwise>标签,接在<when>标签即可)

          <select id="getStuByChoose" resultType="student">
             select * from student 
             <where>
                 <!-- choose选择多种情况中的一种,多种情况符合时选择最前的一种 -->
                 <choose>
                     <when test="id!=null">
                         id = #{id}
                     </when>
                     <when test="name!=null &amp;&amp; name.trim()!=''">
                         name = #{name}
                     </when>
                 </choose>
             </where>
         </select>

    测试1(当只有name值时)

        //测试动态sql的<choose><when><otherwise>
        @Test
        public void testGetStuByChoose() throws IOException {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            Student student = studentMapper.getStuByChoose(new Student(null, "小明"));
            System.out.println(student);
            sqlSession.close();
        }

    测试结果

    测试2(当id和name都有值时)

        //测试动态sql的<choose><when><otherwise>
        @Test
        public void testGetStuByChoose() throws IOException {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            Student student = studentMapper.getStuByChoose(new Student(1, "小明"));
            System.out.println(student);
            sqlSession.close();
        }

    测试结果(因为在<when>中id在前,所以会根据id查询)

  • 相关阅读:
    关于jar项目发布(windows)
    SpringBoot 基础(一) mybatis 通过druid配置多数据库
    redis 基础(二) Redis安装
    测试开发3年,我决定去读个名校硕士
    大厂程序员凡尔赛的一天
    假如我拥有字节工牌。。。
    上海有哪些牛逼的互联网公司?
    那些学计算机的女生后来都怎么样了?
    微信支付零花钱刷屏了!5万额度,能花又能借
    清华集训 part1
  • 原文地址:https://www.cnblogs.com/lyh233/p/12359665.html
Copyright © 2011-2022 走看看