SpringBoot+Mybatis

阅读: 评论:0

SpringBoot+Mybatis

SpringBoot+Mybatis

目录

1.什么是SpringBoot及SpringBoot的特点

2.使用Idea创建SpringBoot快速搭建工程

3.SpringBoot常用的配置文件及如何读取配置文件的内容

4.SpringBoot整合数据源

5.SpringBoot整合Mybatis

6.SpringBoot自动装配原理

7.SpringBoot整合Mybatis-Plus

8.SpringBoot整合Swagger2

9.SpringBoot整合定时器-quartz

1.什么是SpringBoot及SpringBoot的特点

1.1什么是SpringBoot

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程 . 理解:spring框架搭建的步骤:[1]依赖 [2]配置文件。 使用springboot可以简化上面的两个步骤。

1.2SpringBoot特点

① 创建独立的 Spring 应用程序

② 嵌入的 Tomcat,无需部署 WAR 文件

③ 简化 Maven 配置

④ 自动配置 Spring

⑤ 提供生产就绪型功能,如指标,健康检查和外部配置

⑥ 开箱即用,没有代码生成,也无需 XML 配置。

2.使用Idea创建SpringBoot快速搭建工程

Idea版本:IntelliJ IDEA 2022.2

2.1联网

3.SpringBoot常用的配置文件及如何读取配置文件的内容

3.1SpringBoot常用的配置文件

porperties格式和yml格式 区别是两者书法风格不同

porperties

 server.port=t-path=/funain

yml

 server:port: 8080servlet:context-path: /funian

不管使用哪个配置文件,他们的名字必须叫application. 如果上面两个配置文件同时存在,而且里面有相同的配置。则properties优先级高于yml优先级。

3.2如何读取配置文件的内容

java为什么需要读取配置文件的内容,我们开发时需要把哪些内容放入配置文件。

OSS:上传文件。accessKeyId,accessKeySecret等,这些内容能写在java源代码中。硬编码文件,不利维护。 我们需要把信息写入配置文件。

读取方式有两种:

第一种方式: 在类上@ConfigurationProperties(prefix="")

 @Data@Component@ConfigurationProperties(prefix = "student")public class Student {private String name;private Integer age;private String address;private String[] hobby;private Map<String,String> map;​}
 student.name=killerstudent.age=18student.address=Indiastudent.hobby[0]=swimmingstudent.hobby[1]=skatingstudent.hobby[2]=playingstudent.map.word1=hellostudent.map.word2=coming
 student:name: killerage: 18address: Indiahobby:- swimming- skating- playingmap:word1: helloword2: coming

第二种使用@Value读取属性:---他只能读取基本类型和String类型。加在属性上

     @Value("${student.name}")private String name;

4.SpringBoot整合数据源

这里使用druid数据源

(1) 导入相关依赖

 <!--        导入mysql依赖--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!--        导入数据源--><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.2.16</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency>

(2) 配置数据源信息

 spring.datasource.druid.driver-class-name&#sql.cj.jdbc.Driverspring.datasource.druid.url=jdbc:mysql://localhost:3306/ssm_db?useSSL=false&serverTimezone=UTCspring.datasource.druid.username=rootspring.datasource.druid.password=123456

(3) 测试

 @SpringBootTestclass SpringBoot09ApplicationTests {@Autowiredprivate DataSource dataSource;@Testpublic void testDataSource(){System.out.println(dataSource);}}

5.SpringBoot整合Mybatis

(1) 导入相关依赖

 <dependency><groupId&batis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.3.0</version></dependency>

(2) 修改配置文件

 #指定映射文件所在路径(默认是以下路径)mybatis.mapper-locations=classpath:mapper/*.xml#mybatis日志文件figuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

(3) mapper接口

 public interface BookMapper {public List<Book> findAll();}

(4) 为mapper接口生成代理实现类

 (5) 测试

 @SpringBootTestclass SpringBoot09ApplicationTests {@Autowiredprivate BookMapper bookMapper;@Testpublic void testFindAll(){List<Book> list = bookMapper.findAll();System.out.println(list);}}

6.SpringBoot自动装配原理

6.1 springboot包扫描原理

包建议大家放在主类所在包或者子包。默认包扫描的是主类所在的包以及子包。

主函数在运行时会加载一个使用@SpringBootApplication标记的类。而该注解是一个复合注解,包含@EnableAutoConfiguration,这个注解开启了自动配置功能。 该注解也是一个复合注解,包含@AutoConfigurationPackage。 该注解中包含@Import({Registrar.class}),这个注解引入Registrar类。该类中存在registerBeanDefinitions,可以获取扫描的包名。

如果需要人为修改扫描包的名称则需要在主类上@ComponentScan(basepackage={"包名"})

6.2 springboot自动装配原理

思考: 有没有自己使用DispatcherServlet. 为什么DispatcherServlet能用。

主函数在运行会执行一个使用@SpringbootApplication注解的类,该注解是一个复合注解,包含@EnableAutoConfiguration, 该注解开启自动配置功能,该注解也是一个复合注解,包含@Import() 该注解需要导入AutoConfigurationImportSelector类。 该类会加载很多自动装配类,而这些自动装配类完成相应的自动装配原理。

7.SpringBoot整合Mybatis-Plus

7.1mybatis-plus概述

MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

我们的愿景是成为 MyBatis 最好的搭档,就像 魂斗罗 中的 1P、2P,基友搭配,效率翻倍。

不能替代mybatis ,以后对于单表操作的所有功能,都可以使用mp完成。但是链表操作的功能还得要校验mybatis.

7.2如何使用mp

(1) 创建一个SpringBoot工程并导入相关依赖

 <?xml version="1.0" encoding="UTF-8"?><project xmlns=".0.0" xmlns:xsi=""xsi:schemaLocation=".0.0 .0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.12.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.funian</groupId><artifactId>SpringBoot_09</artifactId><version>0.0.1-SNAPSHOT</version><name>SpringBoot_09</name><description>SpringBoot_09</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--        导入mysql依赖--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!--        导入mybatis-plus依赖--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.1</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

(2) 配置数据源

 spring.datasource.driver-class-name&#sql.cj.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/ssm_db?useSSL=false&serverTimezone=UTCspring.datasource.username=rootspring.datasource.password=123456​#指定映射文件所在路径(默认是以下路径)mybatis-plus.mapper-locations=classpath:mapper/*.xml#mybatis日志文件figuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

(3) 创建实体类

 @Datapublic class Book implements Serializable {@TableId(type = IdType.AUTO) //标明主键 采用递增策略private Integer id;private String type;private String name;    private String description;}

(4) 为接口生成代理实现类

(5) 测试

 package com.funian;​import com.funian.domain.Book;import com.funian.mapper.BookMapper;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.st.context.SpringBootTest;​import java.util.List;​@SpringBootTestclass SpringBoot09ApplicationTests {@Autowiredprivate BookMapper bookMapper;@Testpublic void testFindAll(){List<Book> list = bookMapper.selectList(null);System.out.println(list);}}

7.3使用mp完成CRUD

//分页查询需要配置拦截器

 @Configuration@MapperScan(basePackages = "com.funian.mapper")public class MybatisPlusConfig {/*** 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)*/@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}​@Beanpublic ConfigurationCustomizer configurationCustomizer() {return configuration -> configuration.setUseDeprecatedExecutor(false);}}

//CRUD

 @Testpublic void testCRUD(){//根据id查询Book book = bookMapper.selectById(1);System.out.println(book);//增加int insert = bookMapper.insert(book);System.out.println(insert);//更新int i = bookMapper.updateById(book);System.out.println(i);//根据id删除int delete = bookMapper.deleteById(14);System.out.println(delete);List<Integer> list = new ArrayList<>();list.add(20);list.add(21);//批量删除bookMapper.deleteBatchIds(list);QueryWrapper<Book> qw = new QueryWrapper<>();qw.gt("id",5);//条件 >qw.like("name","直播");//条件 模糊查询//根据条件查询List<Book> bookList = bookMapper.selectList(qw);System.out.println(bookList);//current 当前页码//size 数据条数IPage<Book> page = new Page<>(1,5);//根据条件分页查询bookMapper.selectPage(page, qw);System.out.println("获取当前页的数据:" &#Records());System.out.println("获取总页数:"&#Pages());System.out.println("获取总数据条数:"&#Total());}

7.4联表使用mp的分页对象

//mapper接口

 public interface StudentMapper extends BaseMapper<Student> {public IPage<Student> selectByPage(IPage<Student> page, @Param("ew") Wrapper<Student> wrapper);}

//实体类

 @Data@NoArgsConstructor@AllArgsConstructorpublic class Student implements Serializable {​@TableId(type = IdType.AUTO)private Integer sid;​private String sname;​​private Integer sage;​private Integer classid;​@TableField(exist = false)private Classes classes;}

//映射文件.xml

 <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapperPUBLIC "-//mybatis//DTD Mapper 3.0//EN"".dtd"><mapper namespace="com.funian.mapper.StudentMapper">​<resultMap id="BaseResultMap" type="com.ity.Student"><id property="sid" column="sid" jdbcType="INTEGER"/><result property="sname" column="sname" jdbcType="VARCHAR"/><result property="sage" column="sage" jdbcType="INTEGER"/><result property="classid" column="classid" jdbcType="INTEGER"/><association property="classes" javaType="com.ity.Classes" autoMapping="true"><id property="cid" column="cid" jdbcType="INTEGER"></id></association></resultMap>​<sql id="Base_Column_List">sid,sname,sage,classid,classesurriculum</sql>​<select id="selectByPage" resultMap="BaseResultMap">select <include refid="Base_Column_List"/> from studentinner join classes on classes.cid = student.classid<if test="ew!=null and ew.sqlSegment!=''"><where>and ${ew.sqlSegment}</where></if></select></mapper>

//测试

 @Testvoid testSelectByPage() {IPage<Student> studentPage = new Page<>();QueryWrapper<Student> qw = new QueryWrapper<>();qw.gt("sage",20);studentMapper.selectByPage(studentPage,qw);System.out.Records());}

8.SpringBoot整合Swagger2

8.1什么是swagger2

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务的接口文档 . 接口: controller相应的路径方法

8.2为什么是swagger2

目前的项目基本都是前后端分离,后端为前端提供接口的同时,还需同时提供接口的说明文档。但我们的代码总是会根据实际情况来实时更新,这个时候有可能会忘记更新接口的说明文档,造成一些不必要的问题。

8.3如何使用接口文档Swagge2

         <!--swagger2依赖--><dependency><groupId>com.spring4all</groupId><artifactId>swagger-spring-boot-starter</artifactId><version>1.9.1.RELEASE</version></dependency><dependency><groupId>com.github.xiaoymin</groupId><artifactId>swagger-bootstrap-ui</artifactId><version>1.7.8</version></dependency>

(2) 创建一个配置类

 @Componentpublic class Swagger2Config {@Beanpublic Docket docket(){Docket docket = new Docket(DocumentationType.SWAGGER_2).groupName("ruyuan").apiInfo(getInfo()).select().apis(RequestHandlerSelectors.basePackage("ller")) //只为ller包下的类生成接口文档.build();return docket;}​private ApiInfo getInfo(){Contact DEFAULT_CONTACT = new Contact("伏念", "/", "110@qq");ApiInfo apiInfo=new ApiInfo("小圣贤庄API", "小圣贤庄API", "4.1.0", "",DEFAULT_CONTACT, "盘古科技", "/", new ArrayList<VendorExtension>());return apiInfo;}}

(3) 开启swagger2注解驱动

 @SpringBootApplication@MapperScan(basePackages = "com.funian.mapper")@EnableSwagger2 //开启swagger2public class SpringBoot08Application {​public static void main(String[] args) {SpringApplication.run(SpringBoot08Application.class, args);}​}

(4) 访问swagger2在线文档

/doc.html

/swagger-ui.html

8.4swagger2常用的注解

使用swagger注解对接口参数加以说明。

@Api(tags="")====使用在controller类上

@ApiOperation(value="")====接口方法上 接口方法加以说明

@ApiParam(value = "",name = "",required = true)

@ApiModel====实体类

@ApiModelProperty===>实体类的属性说明

版本提示:

这里使用springboot 2.3.12.RELEASE

9.SpringBoot整合定时器-quartz

cron在线表达式

定时器: 在指定的时间执行相应的业务代码。

应用场景: 比如: 定时删除OSS中冗余的文件

三十分钟未支付---->取消订单。

定时发送短信---->11.11====>

(1) 导入定时器依赖

 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-quartz</artifactId></dependency>

(2) 配置定时器任务

 @Componentpublic class TimerTasks {@Scheduled(cron = "0/5 * * * * ? ")public void task01(){System.out.println("~~~~~~"+ w());}}

(3) 开启定时器注解驱动

 @SpringBootApplication@MapperScan(basePackages = "com.funian.mapper")@EnableScheduling //开启定时器public class SpringBoot08Application {​public static void main(String[] args) {SpringApplication.run(SpringBoot08Application.class, args);}​}

本文发布于:2024-02-01 10:46:44,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170675560436079.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:SpringBoot   Mybatis
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23