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查询)

 

posted @   Arbitrary233  阅读(418)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示