mybatis, 动态sql 标签的使用

在这里插入图片描述

在这里插入图片描述

select * from student where id in{1001,1002,1003}
集合实际上就是遍历in后面的id值

在没有标签的时候要想执行 in后面的Arraylist集合需要

 public void testfor() {

        ArrayList<Integer> list = new ArrayList<>();
        list.add(1001);
        list.add(1002);
        list.add(1003);

        String sql = "select * from student where id in";
        StringBuilder builder = new StringBuilder("");
        int init = 0;
        int len = list.size();
        //添加开始的(
        builder.append("(");
        for (Integer i : list) {

            builder.append(i).append(",");

        }
        builder.deleteCharAt(builder.length() - 1);
        builder.append(")");
        System.out.println("sql=="+sql+builder);
    }

在这里插入图片描述
dao接口层的代码

//用法 1 传 数组集合
    List<Student> selectForeachOne(List<Integer> idlist);
//用法2传对象
List<Student> selectForeachTwo(List<Student> stulist);

mapper部分代码

  <select id="selectForeachOne" resultType="com.bjpowernode.domain.Student">
        select * from student where id in
        <foreach collection="list" item="myid" open="(" close=")" separator=",">
            #{myid}

        </foreach>
    </select>


    <select id="selectForeachTwo" resultType="com.bjpowernode.domain.Student">
        select * from student where id in
        <foreach collection="list" item="stu" open="(" close=")" separator=",">
        #{stu.id}

        </foreach>
</select>

.java部分代码


    @Test
    public void selectForeachOne() {
        SqlSession sqlSession = MyBatisUntils.getSqlSession();
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        List<Integer> list = new ArrayList<>();
        list.add(1001);
        list.add(1002);
        list.add(1003);
        List<Student> students = mapper.selectForeachOne(list);
        for (Student student : students) {
            System.out.println(student);
        }
    }
    @Test
    public void selectForeachTwo() {
        SqlSession sqlSession = MyBatisUntils.getSqlSession();
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        ArrayList<Student> students = new ArrayList<>();
        Student s1 = new Student();
   s1.setId(1001);
   students.add(s1);
   Student s2=new Student();
   s2.setId(1002);
   students.add(s2);
        List<Student> students1 = mapper.selectForeachTwo(students);
        for (Student student : students1) {
            System.out.println(student);
        }

sql代码片段 就是服用一些代码

步奏
1.先定义 sql 语句,表名,字段等
2.再使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值