springboot+mybatis+thymeleaf+ajax+JQuery 技术整合搭建项目开发环境__04_技术落地(技术选型)

本节进行 mybatis pagehelper 的整合,给整合框架提供分页功能,便于前台分页查询请求的处理

先展示下最终的项目结构:

 

 1.引入依赖包:

 <!-- springboot 整合 mybatis pagehelper -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>

 <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
        </dependency>

2.编写实体类:(使用到了lombok插件 简化代码书写)

package com.company.frame.auth.domain;

import lombok.Data;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import java.io.Serializable;

/**
 * @title: User
 * @projectName springboot-backendframe
 * @Description: TODO
 * @Auther: Cheri
 * @Date: 2019/4/26 11:38
 */
@Data
@Component
public class User implements Serializable {

    private int id;
    private String name;
    @NotNull
    private int age;
    private String password;

    public User(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public User() {
    }
}

3.创建数据库表并插入一些数据便于测试:

-- auto-generated definition
create table user
(
  id       int(32) auto_increment
    primary key,
  name     varchar(32)              not null,
  age      varchar(50) default '18' not null,
  password varbinary(50)            null
);

 4.Mapper接口

package com.company.frame.auth.dao;

import com.company.frame.auth.domain.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * @title: UserMapper
 * @projectName springboot-backendframe
 * @Description: TODO
 * @Auther: Cheri
 * @Date: 2019/4/26 11:43
 */

@Repository
@Mapper
public interface UserMapper {

    User selectUserById(int id);

    User login(String name,String password);

    int register(User user);

    List<User> selectAllUser();

    @Select("select * from user where name=#{0}")
    List<User> selectAllUserByName(String name);

    @Insert("insert into user(name,age) values(#{name},#{age})")
    public int insertUser(User user);

    int updateUser(@Param("user") User user);

    int deleteUserById(int id);

    @Select("SELECT * FROM user where id=#{id}")
    User findUserById(@Param("id") int id);

}

5. Service

package com.company.frame.auth.service;

import com.company.frame.auth.dao.UserMapper;
import com.company.frame.auth.domain.User;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @title: UserService
 * @projectName springboot-backendframe
 * @Description: TODO
 * @Author Cheri
 * @Date: 2019/5/7 18:32
 */
@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    public User findUserById(int id){
        User user =userMapper.findUserById(id);
        return user;
    }

    /**
     * 获取用户策略:先从缓存中获取用户,没有则取数据表中 数据,再将数据写入缓存
     * @param id
     * @return
     */
    public User queryUserById(int id){

        User user = userMapper.selectUserById(id);
        return user;
    }

    public User login(String userName, String passWord) {
        return userMapper.login(userName,passWord);
    }

    public int register(User user) {
        return userMapper.register(user);
    }

    public PageInfo findAllUser(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> users = userMapper.selectAllUser();
        PageInfo<User> userList = new PageInfo<>(users);
        return userList;
    }

    public List<User> findAllUserByName(String name){
        List<User> userList = userMapper.selectAllUserByName(name);
        return userList;
    }

    public int addUser(User user){
        return userMapper.insertUser(user);
    }

    /**
     * 更新用户
     * @param user
     * @return
     */
    public int updateUser(User user) {
        int result = userMapper.updateUser(user);
        return result;
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    public int deleteUserById(int id) {
        int result = userMapper.deleteUserById(id);
        return result;
    }
}

6.Controller

package com.company.frame.auth.controller;

import com.company.frame.auth.domain.User;
import com.company.frame.auth.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.WebApplicationContext;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @title: UserController
 * @projectName springboot-backendframe
 * @Description: TODO
 * @Author Cheri
 * @Date: 2019/5/7 18:32
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("getUser/{id}")
    @ResponseBody
    public String queryUserById(@PathVariable int id){
        return userService.queryUserById(id).toString();
    }

    @RequestMapping("/pageList")
    @ResponseBody
    public PageInfo<User> findUserList(int pageNum, int pageSize) {
        return userService.findAllUser(pageNum, pageSize);
    }

}

我们来测试一下,使用PostMan

编写单元测试的方式测试: 

package com.company.frame;

import com.company.frame.auth.dao.UserMapper;
import com.company.frame.auth.domain.User;
import com.company.frame.auth.service.UserService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootBackendframeApplicationTests {

    @Autowired
    UserMapper userMapper;

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void mapperTest01() {
       User user =  userMapper.findUserById(44);
        System.out.println(user);

    }

    @Test
    public void findAllUserByPage() throws Exception {
        final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("pageNum", "1");
        params.add("pageSize", "4");
        String mvcResult=  mockMvc.perform(MockMvcRequestBuilders.post("/user/pageList")
                .params(params)).andReturn().getResponse().getContentAsString();
        System.out.println("Result === "+mvcResult);
    }


}

运行测试案例 findAllUserByPage控制台输出如下

页面请求效果: 

总结:引入依赖包:

<!-- springboot 整合 mybatis pagehelper -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.5</version>
</dependency>

          编写分页代码:

public PageInfo findAllUser(int pageNum, int pageSize) {
    PageHelper.startPage(pageNum, pageSize);
    List<User> users = userMapper.selectAllUser();
    PageInfo<User> userList = new PageInfo<>(users);
    return userList;
}

 pageNum:页码

pageSize:每一页显示的记录数

发布了234 篇原创文章 · 获赞 12 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/Coder_Boy_/article/details/89926697
今日推荐