初学SpringBoot和SpringBoot整合SSMP

SpringBoot基础学习笔记


创建SpringBoot工程


Application类(引导类)

package com.judy;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class FristSpringBootApplication {

/**
SpringBoot的引导类是Boot工程的执行入口,运行main方法就可以启动项目
SpringBoot工程运行后初始化Spring容器,扫描引导类所在包加载bean
*/
    public static void main(String[] args) {
        SpringApplication.run(FristSpringBootApplication.class, args);
    }

}


pom.xml文件

通过勾选添加maven坐标


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>


    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.7.1version>
        <relativePath/> 
    parent>

    <groupId>com.judygroupId>
    <artifactId>Frist_SpringBootartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>Frist_SpringBootname>
    <description>Frist_SpringBootdescription>
    <properties>
        <java.version>1.8java.version>
    properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
		
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
			
            <version>2.2.2version>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
			
            <scope>testscope>
        dependency>

    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

project>

yml文件(properties文件)


# 修改服务器端口
server:
port: 80
# 修改banner
spring:
  banner:
    location: classpath:banner.txt
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC
    username: root
    password: root
# 数据库相关配置

整合第三方技术

JUnit

  1. 导入测试对应的starter
  2. 测试类使用@SpringBootTest修饰
  3. 使用自动装配的形式添加要测试的对象

注意:

  1. 测试类如果存在于引导类所在包或子包中无需指定引导类
  2. 测试类如果不存在于引导类所在的包或子包中需要通过classes
    属性指定引导类
@SpringBootTest(classes = SpringbootJUnitApplication.class)//测试类注解
class Springboot07JunitApplicationTests {
	@Autowired
	private Service service;
	@Test
	public void testSave(){
		service.save();
	}
}


MyBatis

spring:
   datasource:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/dataBase?serverTimezone=UTC
      username: root
      password: root
@Mapper
public interface UserDao {
	@Select("select * from user")
	public List<User> getAll();
}
@SpringBootTest
class SpringbootMybatisApplicationTests {
     @Autowired
     private Dao dao;
     @Test
     public void testGetById() {
          User user = dao.getById(1);
          System.out.println(user);
     }
}

MyBatis-Plus

手动添加SpringBoot整合MyBatis-Plus的坐标,可以通过mvnrepository获取
<dependency>
      <groupId>com.baomidougroupId>
      <artifactId>mybatis-plus-boot-starterartifactId>
      <version>3.4.3version>
由于SpringBoot中未收录MyBatis-Plus的坐标版本,需要指定对应的Version
dependency>
//定义数据层接口与映射配置,继承BaseMapper
@Mapper
public interface UserDao extends BaseMapper<User> {
}

Druid

# 变更Druid的配置方式
spring:
   datasource:
      druid:
         driver-class-name: com.mysql.cj.jdbc.Driver
         url: jdbc:mysql://localhost:3306/dataBase?serverTimezone=UTC
         username: root
         password: root


<dependency>
	<groupId>com.alibabagroupId>
	<artifactId>druid-spring-boot-starterartifactId>
	<version>1.2.6version>
dependency>

SpringBoot整合SSMP(Spring+SpringMVC+MyBatisPlus)


LomBok:一个Java类库,提供了一组注解,简化POJO实体类开发

<dependency>
	<groupId>org.projectlombokgroupId>
	<artifactId>lombokartifactId>
dependency>


实体类开发:

//@Data  (LomBok)
@Data/*作用:为当前实体类在编译期设置对应的get/set方法,
       toString方法,hashCode方法,equals方法等*/
public class Book {
    private Integer id;
    private String type;
    private String name;
    private String description;
}


数据层开发:

  1. 导入MyBatisPlus与Druid对应的starter
    springboot没有对应版本:( 要自行添加
<dependency>
    <groupId>com.baomidougroupId>
    <artifactId>mybatis-plus-boot-starterartifactId>
    <version>3.4.3version>
dependency>
<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>druid-spring-boot-starterartifactId>
    <version>1.2.6version>
dependency>


  1. 配置数据源与MyBatisPlus对应的基础配置
spring:
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/ssm_db?servierTimezone=UTC
      username: root
      password: root

mybatis-plus:
  global-config:
    db-config:
      table-prefix: tbl_  #数据库对应名称前缀
      id-type: auto     # 主键
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl   # 开启日志


开发Dao接口

@Mapper
//继承BaseMapper并指定泛型
//(MyBatisPlus)Mapper 继承该接口后,无需编写 mapper.xml 文件,即可获得CRUD功能
public interface BookDao extends BaseMapper<Book> {
}

分页功能:

  1. 使用IPage封装分页数据
  2. 分页操作依赖MyBatisPlus分页拦截器实现功能
  3. 借助MyBatisPlus日志查阅执行SQL语句
IPage对象中封装了分页操作中的所有数据
数据
当前页码值
每页数据总量
最大页码值
数据总量

分页操作是在MyBatisPlus的常规操作基础上增强得到,内部是动态的拼写SQL语句,因此需要增强对应的功能,使用MyBatisPlus拦截器实现

@Configuration
public class MpConfig {
    @Bean
    public MybatisPlusInterceptor mpInterceptor() {
        //1.定义Mp拦截器
        MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();
        //2.添加具体的拦截器
        //分页功能拦截器
        mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return mpInterceptor;
    }
}


业务层开发:

//定义接口
public interface BookService {
    boolean save(Book book);
    boolean delete(Integer id);
    boolean update(Book book);
    Book getById(Integer id);
    List<Book> getAll();
    IPage<Book> getByPage(int currentPage,int pageSize);
}
//实现类
@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;
    //bookDao已经继承BaseDao接口
    //内部定义了相关方法
     @Override
    public Boolean save(Book book) {
        return bookDao.insert(book)>0;
    }

    @Override
    public Boolean update(Book book) {
        return bookDao.updateById(book)>0;
    }

    @Override
    public Boolean delete(Integer id) {
        return bookDao.deleteById(id)>0;
    }

    @Override
    public Book getById(Integer id) {
        return bookDao.selectById(id);
    }

    @Override
    public List<Book> getAll() {
        return bookDao.selectList(null);
    }

    @Override
    public IPage<Book> getPage(int currentPage, int pageSize) {
        IPage page = new Page(currentPage,pageSize);
        return bookDao.selectPage(page,null);
    }
}


表现层开发:

表现层消息一致性处理

/*
1. 设计统一的返回值结果类型便于前端开发读取数据
2. 返回值结果类型可以根据需求自行设定,没有固定格式
3. 返回值结果模型类用于后端与前端进行数据格式统一,也称为前后端数据协议
*/
@Data
public class R {
    private Boolean flag;
    private Object data;
    private String msg;

    public R() {
    }

    public R(Boolean flag){
        this.flag = flag;
    }

    public R(Boolean flag, Object data) {
        this.flag = flag;
        this.data = data;
    }

    public R(Boolean flag, String msg) {
        this.flag = flag;
        this.msg = msg;
    }
}

业务消息一致性处理

//作为springMVC的异常处理器
@RestControllerAdvice
public class ProjectExceptionAdvice {
    //拦截所有的异常信息
    @ExceptionHandler
    public R doException(Exception ex){
        ex.printStackTrace();
        return new R(false,"出错了");
    }
}

/**
基于Restful进行表现层接口开发
新增:POST
删除:DELETE
修改:PUT
查询:GET
*/
@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;

    @GetMapping
    public R getAll(){
        return new R(true,bookService.getAll());
    }

    @PostMapping
    public R save(@RequestBody Book book){
        return new R(bookService.save(book));
    }

    @PutMapping
    public R update(@RequestBody Book book){
        return new R(bookService.update(book));
    }

    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id){
        return new R(bookService.delete(id));
    }

    @GetMapping("{id}")
    public R getById(@PathVariable Integer id){
        return new R(true,bookService.getById(id));
    }

   @GetMapping("{current}/{size}")
   public R getPage(@PathVariable int current,@PathVariable int size){
       IPage<Book> page = bookService.getPage(current, size);
       //如果当前页码大于最大页码。则重新执行查询and当前页码值为最大页码数
       if(current > page.getPages()){
           page = bookService.getPage((int)page.getPages(), size);
       }
       return new R(true,page);
   }

}


目录:
初学SpringBoot和SpringBoot整合SSMP_第1张图片
初学SpringBoot和SpringBoot整合SSMP_第2张图片

  1. pom.xml
    配置起步依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.7.0version>
    parent>
    <groupId>com.judygroupId>
    <artifactId>SpringBoot_SSMP_demoartifactId>
    <version>0.0.1-SNAPSHOTversion>

    <properties>
        <java.version>1.8java.version>
    properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>

        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.4.3version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.2.6version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
      
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <version>2.7.0version>
            plugin>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-surefire-pluginartifactId>
                <configuration>
                    <testFailureIgnore>truetestFailureIgnore>
                configuration>
            plugin>
        plugins>
    build>

project>

  1. application.yml
    设置数据源、端口、框架技术相关配置等
server:
  port: 80

spring:
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
      username: root
      password: 123123


mybatis-plus:
  global-config:
    db-config:
      table-prefix: tbl_
      id-type: auto
      # 主键
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 开启日志


  1. dao
    继承BaseMapper、设置@Mapper
package com.judy.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.judy.domain.Book;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

/**
 * @author:Judy
 * ClassName:BookDao
 * package:com.judy.dao
 */
@Mapper
public interface BookDao extends BaseMapper<Book> {

}


  1. service
    调用数据层接口或MyBatis-Plus提供的接口快速开发
package com.judy.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.judy.domain.Book;

import java.util.List;

/**
 * @author:Judy
 * ClassName:BookService
 * package:com.judy.service
 */
public interface BookService {
    Boolean save(Book book);
    Boolean update(Book book);
    Boolean delete(Integer id);
    Book getById(Integer id);
    List<Book> getAll();
    IPage<Book> getPage(int currentPage,int pageSize);
    IPage<Book> getPage(int currentPage,int pageSize,Book book);

}


package com.judy.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.judy.dao.BookDao;
import com.judy.domain.Book;
import com.judy.service.BookService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author:Judy
 * @date:2022/6/19 15:40
 * ClassName:BookServiceImpl
 * package:com.judy.service.Impl
 */
@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;
    @Override
    public Boolean save(Book book) {
        return bookDao.insert(book)>0;
    }

    @Override
    public Boolean update(Book book) {
        return bookDao.updateById(book)>0;
    }

    @Override
    public Boolean delete(Integer id) {
        return bookDao.deleteById(id)>0;
    }

    @Override
    public Book getById(Integer id) {
        return bookDao.selectById(id);
    }

    @Override
    public List<Book> getAll() {
        return bookDao.selectList(null);
    }

    @Override
    public IPage<Book> getPage(int currentPage, int pageSize) {
        IPage page = new Page(currentPage,pageSize);
        return bookDao.selectPage(page,null);
    }

}


  1. controller
    基于Restful开发
package com.judy.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.judy.controller.utils.R;
import com.judy.domain.Book;
import com.judy.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author:Judy
 * ClassName:BookController
 * package:com.judy.controller
 */
@RestController
@RequestMapping("/books")
public class BookControllerR {
    @Autowired
    private BookService bookService;

    @GetMapping
    public R getAll(){
        return new R(true,bookService.getAll());
    }

    @PostMapping
    public R save(@RequestBody Book book){
        return new R(bookService.save(book));
    }

    @PutMapping
    public R update(@RequestBody Book book){
        return new R(bookService.update(book));
    }

    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id){
        return new R(bookService.delete(id));
    }

    @GetMapping("{id}")
    public R getById(@PathVariable Integer id){
        return new R(true,bookService.getById(id));
    }

   @GetMapping("{current}/{size}")
   public R getPage(@PathVariable int current,@PathVariable int size){
       IPage<Book> page = bookService.getPage(current, size);
       //如果当前页码大于最大页码。则重新执行查询and当前页码值为最大页码数
       if(current > page.getPages()){
           page = bookService.getPage((int)page.getPages(), size);
       }
       return new R(true,page);
   }


}


  1. 其他:
package com.judy.controller.utils;

import lombok.Data;

/**
 * @author:Judy
 * ClassName:R
 * package:com.judy.controller.utils
 */
@Data
public class R {
    private Boolean flag;
    private Object data;
    private String msg;

    public R() {
    }

    public R(Boolean flag){
        this.flag = flag;
    }

    public R(Boolean flag, Object data) {
        this.flag = flag;
        this.data = data;
    }

    public R(Boolean flag, String msg) {
        this.flag = flag;
        this.msg = msg;
    }
}


package com.judy.controller.utils;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author:Judy
 * ClassName:ProjectExceptionAdvice
 * package:com.judy.controller.utils
 */
//作为springMVC的异常处理器
@RestControllerAdvice
public class ProjectExceptionAdvice {
    //拦截所有的异常信息
    @ExceptionHandler
    public R doException(Exception ex){
        //
        ex.printStackTrace();
        return new R(false,"BOOMMMM!!!!");
    }
}


package com.judy.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author:Judy
 * ClassName:MPconfig
 * package:com.judy.config
 */
@Configuration//配置类
public class MPconfig {
    @Bean//第三方Bean交给spring管理
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        //分页功能拦截器
        return mybatisPlusInterceptor;
    }
}

你可能感兴趣的:(spring,boot,java,mybatis)