聚合查询和模糊查询

聚合查询

测试类中的代码为:
使用map集合

//聚合查询
    @Test
    public void test4(){
        UsersDao dao=new UsersDaoImpl();
        Map m=dao.jisuan();
        System.out.println(m.get("MAX"));
    }

输出查询的结果 .get("")

实现类中的代码为:

//聚合查询
    public Map jisuan(){
        SqlSession session=su.getsession();
        Map m= (Map) session.selectOne("jisuan");
        return m;
    }

selectOne查询结果为一条

mapper文件中的代码为:

<select id="jisuan" resultType="Map">
        SELECT MAX(studentno) MAX,MIN(studentno) MIN,AVG(studentno) AVG FROM students;
    </select>

返回的结果集为map,
resultType属性决定返回类型,
聚合查询的结果去别名方便取出

模糊查询

三种存放数据的方式

  1. 数组
  2. list集合
  3. map集合

使用数组

测试类中代码

 //使用数组查询用户
    @Test
     public void test7() {
        sessionUtil s=new sessionUtil();
        SqlSession session=s.getsession();
        UsersDao dao=session.getMapper(UsersDao.class);
        int[] ids = {1, 2, 3, 4};
        List<Users> users = dao.findarray(ids);
        System.out.println(users);
    }

省略接口实现类中代码的方式
getMapper(类名.class)

mapper中文件的代码为:

<select id="findarray"  resultType="Users">
        SELECT * FROM students WHERE studentno IN (<foreach collection="array" item="id"  separator=",">#{id}</foreach>)
    </select>

用 foreach对数组或者集合中的数据进行遍历
foreach属性的介绍,以下链接

https://blog.csdn.net/czd3355/article/details/75340080

使用list集合
测试类中的代码为:

 //使用List集合查找指定的id用户
    @Test
    public void test5(){

        sessionUtil s=new sessionUtil();
        SqlSession session=s.getsession();
        System.out.println(session);
        UsersDao dao=session.getMapper(UsersDao.class);
        //list存储需要查找的ids
        List ids=new ArrayList();
        ids.add(1);
        ids.add(3);
        ids.add(4);
        ids.add(5);
        List<Users> list=dao.findbyids(ids);
        for (Users users:list){
            System.out.println(users);
        }
    }

mapper文件的代码为:

<select id="findbyids" resultType="Users">
        SELECT * FROM students WHERE studentno IN <foreach collection="list" item="id" open="(" close=")" separator=",">#{id}</foreach>
    </select>

使用mapper集合

测试类中的代码为:

 //使用map集合模糊查询
    @Test
    public  void test6(){
        sessionUtil s=new sessionUtil();
        SqlSession session=s.getsession();
        UsersDao dao=session.getMapper(UsersDao.class);
        //使用map集合存放数据
        Map m=new HashMap();
        m.put("studentname","张");
        List<Users> list=dao.findidmap(m);
        System.out.println(list);
    }

mapper文件的代码:

<select id="findidmap" resultType="Users" ><!--parameterType="map",属性可添加-->
        SELECT * FROM students WHERE 1=1
        <if test="studentname!=null and studentname!=''"><!--且语句用and  而不是&&-->
            and  studentname like '%${studentname}%'
        </if>
    </select>

猜你喜欢

转载自blog.csdn.net/fdk2zhang/article/details/82944064
今日推荐