从零搭建 Spring Boot 后端项目(二)

桃扇骨 2023-02-28 05:41 237阅读 0赞

简介

这一小节主要是整合mybatis、Druid连接池、PageHelper分页

步骤

  • 在之前的开发依赖界面中,我们可以选择所需要的依赖,当然我们也可以手动添加依赖,以在项目中整合mybatis、Druid连接池、PageHelper分页,在pom.xml 文件中添加如下依赖

    1. <!-- mysql数据库驱动-->
    2. <dependency>
    3. <groupId>mysql</groupId>
    4. <artifactId>mysql-connector-java</artifactId>
    5. <scope>runtime</scope>
    6. </dependency>
    7. <!-- druid 数据库连接池-->
    8. <dependency>
    9. <groupId>com.alibaba</groupId>
    10. <artifactId>druid-spring-boot-starter</artifactId>
    11. <version>1.1.10</version>
    12. </dependency>
    13. <!-- mybatis -->
    14. <dependency>
    15. <groupId>org.mybatis.spring.boot</groupId>
    16. <artifactId>mybatis-spring-boot-starter</artifactId>
    17. <version>2.1.0</version>
    18. </dependency>
    19. <!-- pagehelper -->
    20. <dependency>
    21. <groupId>com.github.pagehelper</groupId>
    22. <artifactId>pagehelper-spring-boot-starter</artifactId>
    23. <version>1.2.5</version>
    24. </dependency>

    注:有时输入正确,但 pom.xml 文件仍然报错,此时考虑依赖并未下载完全,可使用Maven的Reimport功能重新导入即可
    在这里插入图片描述

  • 配置 application-dev.properties 文件,在该配置文件内配置以下内容

    1. # 开发环境配置文件
    2. # Druid
    3. # 数据连接池的类型
    4. spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
    5. # 数据连接池的名称
    6. spring.datasource.name=druid_datasource
    7. # 数据库驱动、url、用户名和密码
    8. spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
    9. spring.datasource.druid.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true
    10. spring.datasource.druid.username=root
    11. spring.datasource.druid.password=password
    12. # 配置连接池初始化大小、最大值、最小值
    13. spring.datasource.druid.initial-size=20
    14. spring.datasource.druid.max-active=40
    15. spring.datasource.druid.min-idle=1
    16. # 获取连接等待超时时间
    17. spring.datasource.druid.max-wait=60000
    18. # 间隔多久进行一次检测,检测需要关闭的空闲连接
    19. spring.datasource.druid.time-between-eviction-runs-millis=60000
    20. # 一个连接在池中最小生存的时间
    21. spring.datasource.druid.min-evictable-idle-time-millis=300000
    22. # 检测连接是否有效
    23. spring.datasource.druid.validation-query=SELECT 1 FROM DUAL
    24. spring.datasource.druid.test-while-idle= true
    25. spring.datasource.druid.test-on-borrow= false
    26. spring.datasource.druid.test-on-return= false
    27. # Mybatis
    28. # mapper映射xml文件的所在路径
    29. mybatis.mapper-locations=classpath*:mapper/*.xml
    30. # 对应实体类的路径
    31. mybatis.type-aliases-package=com.example.backend_template.entity
    32. # 开启驼峰命名
    33. mybatis.configuration.map-underscore-to-camel-case=true
    34. # Pagehelper
    35. # 指定数据库
    36. pagehelper.helperDialect=mysql
    37. # 是否支持接口参数来传递分页参数
    38. pagehelper.supportMethodsArguments=true
  • 配置 application.properties 文件,在该配置文件内配置以下内容

    1. spring.profiles.active=dev

测试

接下来测试一下,目前搭的框架有没有问题

  • 创建数据库和数据表

    1. CREATE DATABASE test;
    2. use test;
    3. CREATE TABLE `tb_user` (
    4. `id` int(11) NOT NULL,
    5. `username` varchar(255) DEFAULT NULL,
    6. `password` varchar(255) DEFAULT NULL,
    7. PRIMARY KEY (`id`)
    8. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    9. INSERT INTO `tb_user` VALUES ('1', 'AA', '112233');
    10. INSERT INTO `tb_user` VALUES ('2', 'BB', '123456');
    11. INSERT INTO `tb_user` VALUES ('3', 'CC', '123456');
    12. INSERT INTO `tb_user` VALUES ('4', 'DD', '123456');
    13. INSERT INTO `tb_user` VALUES ('5', 'EE', '123456');
    14. INSERT INTO `tb_user` VALUES ('6', 'FF', '123456');
  • com.example.backend_template.entity下新建实体类User

    1. package com.example.backend_template.entity;
    2. import java.io.Serializable;
    3. /**
    4. * @ClassName User
    5. * @Description
    6. * @Author L
    7. * @Date Create by 2020/6/25
    8. */
    9. public class User implements Serializable {
    10. private Long id;//编号
    11. private String username;//用户名
    12. private String password;//密码
    13. public Long getId() {
    14. return id;
    15. }
    16. public void setId(Long id) {
    17. this.id = id;
    18. }
    19. public String getUsername() {
    20. return username;
    21. }
    22. public void setUsername(String username) {
    23. this.username = username;
    24. }
    25. public String getPassword() {
    26. return password;
    27. }
    28. public void setPassword(String password) {
    29. this.password = password;
    30. }
    31. }
  • com.example.backend_template.dao下新建UserDao类,需要使用@Mapper注解,不然SpringBoot无法扫描

    1. package com.example.backend_template.dao;
    2. import com.example.backend_template.entity.User;
    3. import org.apache.ibatis.annotations.Mapper;
    4. import java.util.List;
    5. /**
    6. * @ClassName UserDao
    7. * @Description
    8. * @Author L
    9. * @Date Create by 2020/6/25
    10. */
    11. @Mapper//指定这是一个操作数据库的mapper
    12. public interface UserDao {
    13. List<User> findAll();
    14. }
  • resources.mapper下创建UserDao.xml

    • namespace中需要与使用@Mapper的接口对应
    • UserDao.xml文件名称必须与使用@Mapper的接口一致
    • 标签中的id必须与@Mapper的接口中的方法名一致,且参数一致

      <?xml version=”1.0” encoding=”UTF-8” ?>
      <!DOCTYPE mapper PUBLIC “-//mybatis.org//DTD Mapper 3.0//EN” “http://mybatis.org/dtd/mybatis-3-mapper.dtd“ >



  • com.example.backend_template.service下创建UserService接口

    1. package com.example.backend_template.service;
    2. import com.example.backend_template.entity.User;
    3. import java.util.List;
    4. /**
    5. * @ClassName UserService
    6. * @Description
    7. * @Author L
    8. * @Date Create by 2020/6/25
    9. */
    10. public interface UserService {
    11. List<User> findAll();
    12. List<User> findAll(Integer page,Integer size);
    13. }
  • com.example.backend_template.service.impl下创建UserServiceImpl实现类

    • 需要在接口实现类中使用@Service注解,才能被SpringBoot扫描,在Controller中使用@Authwired注入

      package com.example.backend_template.service.impl;

      import com.example.backend_template.dao.UserDao;
      import com.example.backend_template.entity.User;
      import com.example.backend_template.service.UserService;
      import com.github.pagehelper.PageHelper;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.stereotype.Service;

      import java.util.List;

      /**

      • @ClassName UserServiceImpl
      • @Description
      • @Author L
      • @Date Create by 2020/6/25
        */
        @Service(“userService”)
        public class UserServiceImpl implements UserService {

        @Autowired
        private UserDao userDao;

        @Override
        public List findAll() {

        1. return userDao.findAll();

        }

        @Override
        public List findAll(Integer page, Integer size){

        1. //开启分页查询,只有紧跟的第一个查询有效
        2. //第一个参数为查询第几页,第二个为页面大小
        3. PageHelper.startPage(page,size);
        4. List<User> userList = userDao.findAll();
        5. return userList;

        }
        }

  • com.example.backend_template.controller下创建UserController类

    1. package com.example.backend_template.controller;
    2. import com.example.backend_template.entity.User;
    3. import com.example.backend_template.service.UserService;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.web.bind.annotation.RequestMapping;
    6. import org.springframework.web.bind.annotation.RequestParam;
    7. import org.springframework.web.bind.annotation.RestController;
    8. import java.util.List;
    9. /**
    10. * @ClassName UserController
    11. * @Description
    12. * @Author L
    13. * @Date Create by 2020/7/3
    14. */
    15. @RestController
    16. @RequestMapping("/user")
    17. public class UserController {
    18. @Autowired
    19. private UserService userService;
    20. @RequestMapping("/findAll")
    21. public List<User> findAll(){
    22. return userService.findAll();
    23. }
    24. @RequestMapping("/find")
    25. public List<User> findAll(@RequestParam(defaultValue = "0") Integer page,
    26. @RequestParam(defaultValue = "0") Integer size) {
    27. return userService.findAll(page, size);
    28. }
    29. }
  • 在启动类中添加对@MapperScan的扫描

    1. package com.example.backend_template;
    2. import org.mybatis.spring.annotation.MapperScan;
    3. import org.springframework.boot.SpringApplication;
    4. import org.springframework.boot.autoconfigure.SpringBootApplication;
    5. @SpringBootApplication
    6. @MapperScan("com.example.backend_template.dao")//使用MapperScan批量扫描所有的Mapper接口;
    7. public class BackendTemplateApplication {
    8. public static void main(String[] args) {
    9. SpringApplication.run(BackendTemplateApplication.class, args);
    10. }
    11. }
  • 启动springboot ,不分页情况下,访问 http://localhost:8080/user/findAll ,结果如下
    在这里插入图片描述
  • 分页情况下,访问http://localhost:8080/user/find?page=2&size=2 ,结果如下
    在这里插入图片描述
    如出现以上两种结果则到表明框架整合成功。测试完后,就可以把从测试开始新建的文件和注解删除了,之后会新加其它的文件,但这里数据库暂时不要删除,之后换数据库的时候再删也不迟

项目地址

项目介绍:从零搭建 Spring Boot 后端项目
代码地址:https://github.com/xiaoxiamo/backend-template

下一篇

三、整合Redis

发表评论

表情:
评论列表 (有 0 条评论,237人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Spring Boot 项目

    简介 一个基于 Spring Boot 的后端开发模板,主要用于减少平时重复的工作量,以及使开发有良好的开发规范,主要功能包括但不限于权限管理、在线接口文档、日志记录、单