18-Mybatis动态sql之四 -- <sql>代码片段

该博客介绍了Mybatis中如何使用<foreach>标签进行动态SQL拼接,通过示例展示了在mapper.xml中定义sql片段并用include引入,以及如何传入实体类list作为参数进行条件查询。测试结果显示成功执行了根据id列表查询学生信息的操作。
摘要由CSDN通过智能技术生成

前一篇:17-Mybatis动态sql之三 – < foreach>标签https://blog.csdn.net/fsjwin/article/details/109678982

对于在mapper.xml中重复度较高的代码可以出去出代码片段,然后include引入就可以了,记住了没有那么复杂就是string移过来就可以了。

  1. 定义
  2. 使用

使用17章的例子仅修改mapper.xml接口

1. StudentDao

wwwwwwwwwwwwwwwwwwwwww

    //foreach-动态sql 必须参数为实体类list,不能是其他的情况
    public List<Student> selectStudentforeach2(@Param("studentList") List<Student> studentList);


2. StudentDao.xml

在这里插入图片描述

 <sql id="studentSql">
        select id,name,email,age from student
    </sql>



    <select id="selectStudentforeach2"  resultType="com.yuhl.domain.Student">
        <include refid="studentSql"></include> where id in
        <foreach collection="studentList" item="stu" open="(" close=")" separator=",">
            #{stu.id}
        </foreach>

    </select>

3. 测试

  @Test
    public void test21() {
        SqlSession sqlsession = MybatisUtil.getSqlsession();
        StudentDao studentDao = sqlsession.getMapper(StudentDao.class);
        //可以吧查询的条件放进去,也可以使用一个单独的类ParaObject类封装就可以了。

        List<Student> list = new ArrayList();
        list.add(new Student(1001, "张三", "qq.com", 10));
        list.add(new Student(1002, "张三", "qq.com", 10));
        list.add(new Student(1003, "张三", "qq.com", 10));
        List<Student> studentList = studentDao.selectStudentforeach2(list);
        studentList.forEach(stu -> System.out.println(stu));
    }

4. 测试结果

PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 230528013.
==>  Preparing: select id,name,email,age from student where id in ( ? , ? , ? )
==> Parameters: 1001(Integer), 1002(Integer), 1003(Integer)
<==    Columns: id, name, email, age
<==        Row: 1001, 张三, zhangsan@qq.com, 20
<==        Row: 1002, 李四, lisi@qq.com, 28
<==        Row: 1003, yuhl, yuhl@163.com, 20
<==      Total: 3
Student{id=1001, name='张三', email='zhangsan@qq.com', age=20}
Student{id=1002, name='李四', email='lisi@qq.com', age=28}
Student{id=1003, name='yuhl', email='yuhl@163.com', age=20}

Process finished with exit code 0

下一篇:19-Mybatis分页小工具https://blog.csdn.net/fsjwin/article/details/109684099

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值