SpringBoot 学习——Mybatis注解方式+PageHelper

参考博客:Spring Boot干货系列:(九)数据存储篇-SQL关系型数据库之MyBatis的使用

 

Mybatis注解的方式比较简单,只要定义一个dao接口,然后sql语句通过注解写在接口方法上。最后给这个接口添加@Mapper注解或者在启动类上添加@MapperScan(“com.springboot.dao”)注解都行。

添加依赖

 如果使用分页插件pagehelper的话,需要在pom.xml中添加依赖。


    org.mybatis.spring.boot
    mybatis-spring-boot-starter
    1.3.2



    mysql
    mysql-connector-java



    com.alibaba
    fastjson
    1.2.31



    org.apache.commons
    commons-lang3
    3.3



    com.github.pagehelper
    pagehelper-spring-boot-starter
    1.2.10

这里不引入spring-boot-starter-jdbc依赖,是由于mybatis-spring-boot-starter中已经包含了此依赖。

MyBatis-Spring-Boot-Starter依赖将会提供如下:

  • 自动检测现有的DataSource
  • 将创建并注册SqlSessionFactory的实例,该实例使用SqlSessionFactoryBean将该DataSource作为输入进行传递
  • 将创建并注册从SqlSessionFactory中获取的SqlSessionTemplate的实例。
  • 自动扫描您的mappers,将它们链接到SqlSessionTemplate并将其注册到Spring上下文,以便将它们注入到您的bean中。

就是说,使用了该Starter之后,只需要定义一个DataSource即可(application.properties中可配置),它会自动创建使用该DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。会自动扫描你的Mappers,连接到SqlSessionTemplate,并注册到Spring上下文中。

应用配置

在src/main/resources/application.properties中配置数据源信息:

spring.datasource.url = jdbc:mysql://localhost:3306/spring?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = root0
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver

在使用@Mapper注解方式代替XXmapper.xml配置文件、使用@Select等注解配置SQL语句的情况下,配置数据库字段名到JavaBean实体类属性命的自动驼峰命名转换:

# 设为true表示开启驼峰转换
mybatis.configuration.mapUnderscoreToCamelCase=true

基本代码模块

实体对象:

public class LearnResource {
    private Long id;
    private String author;
    private String title;
    private String url;

    //get & set 方法
}

Controller层:

@Controller
@RequestMapping("/learn")
public class LearnController {
    @Autowired
    private LearnService learnService;

    @RequestMapping("t")
    public String learn(){
        return "learn-resource";
    }

    @RequestMapping(value = "queryLearnList",method = RequestMethod.POST,produces="application/json;charset=UTF-8")
    @ResponseBody
    public void queryLearnList(HttpServletRequest request , HttpServletResponse response){
        int page = Integer.parseInt(request.getParameter("page")); // 取得当前页数,注意这是jqgrid自身的参数
        int rows = Integer.parseInt(request.getParameter("rows")); // 取得每页显示行数,,注意这是jqgrid自身的参数
        PageInfo pageObj =learnService.queryLearnResourceList(page, rows);
        List> learnList=pageObj.getList();
        JSONObject jo=new JSONObject();
        jo.put("rows", learnList); //包含实际数据的数组
        jo.put("total", pageObj.getPages()); //总页数
        jo.put("records", pageObj.getTotal()); //查询出的记录数
        ServletUtil.createSuccessResponse(200, jo, response);
    }

    /**
     * 新添教程
     * @param request
     * @param response
     */
    @RequestMapping(value = "add",method = RequestMethod.POST)
    public void addLearn(HttpServletRequest request , HttpServletResponse response){
        JSONObject result=new JSONObject();
        String author = request.getParameter("author");
        String title = request.getParameter("title");
        String url = request.getParameter("url");
        if(author.isEmpty()){
            result.put("message","作者不能为空!");
            result.put("flag",false);
            ServletUtil.createSuccessResponse(200, result, response);
            return;
        }
        if(title.isEmpty()){
            result.put("message","教程名称不能为空!");
            result.put("flag",false);
            ServletUtil.createSuccessResponse(200, result, response);
            return;
        }
        if(url.isEmpty()){
            result.put("message","地址不能为空!");
            result.put("flag",false);
            ServletUtil.createSuccessResponse(200, result, response);
            return;
        }
        LearnResource learnResource = new LearnResource();
        learnResource.setAuthor(author);
        learnResource.setTitle(title);
        learnResource.setUrl(url);
        int index=learnService.add(learnResource);
        System.out.println("结果="+index);
        if(index>0){
            result.put("message","教程信息添加成功!");
            result.put("flag",true);
        }else{
            result.put("message","教程信息添加失败!");
            result.put("flag",false);
        }
        ServletUtil.createSuccessResponse(200, result, response);
    }

    /**
     * 删除教程
     * @param request
     * @param response
     */
    @RequestMapping(value="delete",method = RequestMethod.POST)
    @ResponseBody
    public void deleteUser(HttpServletRequest request ,HttpServletResponse response){
        String id = request.getParameter("ids");
        System.out.println("ids==="+id);
        JSONObject result = new JSONObject();
        //删除操作
        int index = learnService.delete(id);
        if(index>0){
            result.put("message","教程信息删除成功!");
            result.put("flag",true);
        }else{
            result.put("message","教程信息删除失败!");
            result.put("flag",false);
        }
        ServletUtil.createSuccessResponse(200, result, response);
    }
}

Service层接口及实现:

package com.springboot.service;
import com.github.pagehelper.PageInfo;
import com.springboot.entity.LearnResource;

public interface LearnService {
    int add(LearnResource learnResource);
    int delete(String id);
    PageInfo queryLearnResourceList(int page, int size);

}
@Service
public class LearnServiceImpl implements LearnService {
    @Autowired
    LearnMapper learnMapper;

    @Override
    public int add(LearnResource learnResource) {
        return this.learnMapper.add(learnResource);
    }

    @Override
    public int delete(String id) {
        return this.learnMapper.delete(id);
    }

    @Override
    public PageInfo queryLearnResourceList(int page, int size) {
        PageHelper.startPage(page, size);
        List learnResourceList = learnMapper.learnResourceList();
        PageInfo pageInfoDemo = new PageInfo(learnResourceList);
        return pageInfoDemo;
    }
}

使用PageHelper时,在查询list之前使用PageHelper.startPage(int pageNum, int pageSize)方法。其中pageNum是第几页,pageSize是每页多少条。

分页插件PageHelper项目地址: https://github.com/pagehelper/Mybatis-PageHelper

Dao接口:

@Mapper
public interface LearnMapper {
    @Insert("insert into learn_resource(author, title,url) values(#{author},#{title},#{url})")
    int add(LearnResource learnResource);

    @Delete("delete from learn_resource where id = #{id}")
    int delete(String id);

    @Select("select * from learn_resource order by id")
    List learnResourceList();
}

最终项目效果如下,实现了对数据库的部分基本操作。

SpringBoot 学习——Mybatis注解方式+PageHelper_第1张图片

你可能感兴趣的:(Web)