Use limit in mybatis to realize paging and the usage of Map

1. Limit realizes paging

Limit exists in sql, which can realize paging query. Its usage is:

select * from table1 limit startIndex,pageStze
--这里的startIndex与pageSize在使用时用整数代替

As the name implies, limit requires two parameters: startIndex is the actual subscript that identifies the page, which is the number of records from the first page to be displayed; pageSize is the number of records displayed on each page. such as:

select * from table1 limit 35

It means that starting from the third record in the table, every five records are displayed as a page. These two parameters can be passed in in mybatis.

2. How to use Map

To use Map, you must first import the util package (Of course, IDEA can automatically import it)
The core of Map is key-value pairs. You can understand it directly after you use it. The code:

HashMap<String,Integer> map = new HashMap<String,Integer>();
map.put("startIndex",0);
map.put("pageSize",3);

Create an instance of Map, HashMap<String,Integer> is the "structure" that defines key-value pairs, String is the type of key (key), and Integer is the type of value (value) of this key, of course this can be set by yourself. Then you can call the put() method of the Map instance to store a key-value pair. Of course, a Map instance can store multiple key-value pairs. It is more convenient to use Map to transfer parameters.

3. Implement paging query in mybatis

This is no different from the previous query, except that limit is used on the SQL statement. The code above:
writing methods in the interface

    //分页测试
    List<User> getUserByLimit(Map<String,Integer> map);

"Implement" this method in the configuration (note that the parameter in the map is #{key name})

    <!--使用map来传参-->
    <select id="getUserByLimit" parameterType="map" resultType="User">
        <!--limit后面跟两个参数,第一个参数是显示分页的起始下标,第二个是页面的大小-->
        select * from mybatis.user limit #{startIndex},#{pageSize};
    </select>

test

    @Test
    public void limitTest00(){
    
    
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserDao mapper = sqlSession.getMapper(UserDao.class);

        //创建map来存放参数,map就是键值对,定义时HashMap<String,Integer>转下一行
        //String就是key的类型,Integer就是这个健的值的类型,当然这两个类型可自行设置
        HashMap<String,Integer> map = new HashMap<String,Integer>();
        map.put("startIndex",0);
        map.put("pageSize",3);

        List<User> usersByPage = mapper.getUserByLimit(map);

        for(User user:usersByPage){
    
    
            System.out.println(user.getId());
        }

    }

Guess you like

Origin blog.csdn.net/kitahiragawa/article/details/113055538