Springboot mybatis-plus

1.什么是Springboot

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化Spring应用的创建、运行、调试、部署等。使用Spring Boot可以做到专注于Spring应用的开发,而无需过多关注XML的配置。Spring Boot使用“习惯优于配置”的理念,简单来说,它提供了一堆依赖打包,并已经按照使用习惯解决了依赖问题。使用Spring Boot可以不用或者只需要很少的Spring配置就可以让企业项目快速运行起来。

2.SpringBoot的特点

(1) 用来简化Spring应用的初始搭建以及开发过程,使用特定的方式来配置

(2)创建独立的Spring引用程序main方法运行

(3)嵌入的tomcat无需部署war文件

(4)简化maven配置

(5)自动配置Spring添加对应的功能starter自动化配置

3.使用idea快速搭建springboot工程

1.搭建环境

(1)jdk1.8

(2)idea 2022.2.2

(3)win11

2.在有网的情况下

Springboot mybatis-plus_第1张图片

 Springboot mybatis-plus_第2张图片

3.创建一个controller

@RestController
public class springController {
    @GetMapping("index")
    public Map spring() {
        Map map = new HashMap<>();
        map.put("name", "张明喆");
        map.put("age", 20);
        return map;
    }

浏览器访问接口

Springboot mybatis-plus_第3张图片

4.springboot常用配置文件

  1. properties和yml 两种格式

  2. (1)properties:
    #修改端口号
    server.port=9999
    #修改访问路径
    server.servlet.context-path=/aaa

    (2)yml:

    server:
      port: 8888
      servlet:
        context-path: /bbb

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

    5.java如何读取配置文件中的内容

    1.第一种方式:

    使用@ConfigurationProperties获取配置文件

@Data
@Component
@ConfigurationProperties(prefix = "student")
public class Student {
    private String name;
    private Integer age;
    private String address;
    private List hobby;
    private Map map;
}

Springboot mybatis-plus_第4张图片

 Springboot mybatis-plus_第5张图片

2.第二种方式:使用@Value获取配置文件--只能读取基本类型和String类型

@Value("${student.name}")
    private String name;
    @GetMapping("n")
    public String m() {
        return name;
    }
    @Value("${student.age}")
    private Integer age;
    @GetMapping("a")
    public Integer a() {
        return age;
    }

6. springboot整合数据源

连接数据库

(1)引入依赖


            com.alibaba
            druid-spring-boot-starter
            1.2.16
        
        
            com.mysql
            mysql-connector-j
        
        
            org.springframework.boot
            spring-boot-starter-jdbc
        

(2)配置数据源信息

spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.url=jdbc:mysql://localhost:3306/aaa
spring.datasource.druid.username=root
spring.datasource.druid.password=17637422471
spring.datasource.druid.initial-size=5

(3)测试类测试

@SpringBootTest
class Springbootqy163ApplicationTests {
@Autowired
private DataSource dataSource;
    @Test
    void contextLoads() throws SQLException {
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        System.out.println(dataSource);
    }
}
​

7.springboot整合mybatis

(1)相关依赖


    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.7.10
         
    
    com.sws
    qy163-springboot02
    0.0.1-SNAPSHOT
    qy163-springboot02
    Demo project for Spring Boot
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        
​
          
            com.mysql
            mysql-connector-j
        
        
       
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.1.4
        
        
            com.alibaba
            druid-spring-boot-starter
            1.2.16
        
​
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    
​
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            org.projectlombok
                            lombok
                        
                    
                
            
        
    

(2)修改配置文件

#数据源
spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.username=root
spring.datasource.druid.password=17637422471
spring.datasource.druid.url=jdbc:mysql://localhost:3306/aaa
​
#指定映射文件所在的路径--
mybatis.mapper-locations=classpath:mapper/*.xml
​
#mybatis日志文件
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

(3)mapper接口

public interface EmpMapper {
    public List findAll();
}

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

Springboot mybatis-plus_第6张图片

(5)测试

@SpringBootTest
class DemoApplicationTests {
​
    @Autowired
    private EmpMapper empMapper;
    @Test
    void contextLoads() {
        System.out.println(empMapper.findAll());
    }
​
}
​

2---springboot装配原理mybatis-puls整合

2.springboot自动装配原理

2.1springboot包扫描原理

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

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

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

2.2 springboot自动装配原理

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

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

3.springboot整合mybatis-plus(MP)

3.1mybatis-plus概述

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

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

Springboot mybatis-plus_第7张图片

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

3.2如何使用mybatis-plus(MP)

(1)创建表并加入数据

DELETE FROM user;
​
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');

(2)创建一个springboot工程并引入相关的依赖


    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.7.10
         
    
    com.sws
    qy163-springboot02
    0.0.1-SNAPSHOT
    qy163-springboot02
    Demo project for Spring Boot
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        
​
          
            com.mysql
            mysql-connector-j
        
       
            com.baomidou
       mybatis-plus-boot-starter
            3.5.1
        
       
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.1.4
        
        
            com.alibaba
            druid-spring-boot-starter
            1.2.16
        
​
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    
​
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            org.projectlombok
                            lombok
                        
                    
                
            
        
    

(3)配置数据源

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=17637422471
spring.datasource.url=jdbc:mysql:///aaa

(4)创建实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

(5)创建一个mapper接口

public interface UserMapper extends BaseMapper {
}

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

@SpringBootApplication
@MapperScan(basePackages = "com.sws.mapper")
public class DemoApplicationTests {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplicationTests.class, args);
    }
​
}

(7)测试

@SpringBootTest
class DemoApplicationTests {
​
    @Autowired
    private UserMapper userMapper;
    @Test
    void test() {
        User user = userMapper.selectById(8);
        System.out.println(user);
    }
​
}

3.3 使用mp完成CRUD

@SpringBootTest
class DemoApplicationTests {
    @Autowired
    private UserMapper userMapper;
​
@Test
public void  select(){
    QueryWrapper wrapper=new QueryWrapper<>();
    wrapper.likeRight("name","_明");
    wrapper.or();
    wrapper.between("age",18,24);
    List list = userMapper.selectList(wrapper);
    System.out.println(list);
}
    @Test
    public void deleteById(){
        int i = userMapper.deleteById(4);
        System.out.println(i);
    }
@Test
public void delete(){
    List list=new ArrayList<>();
    list.add(2);
    list.add(3);
    userMapper.deleteBatchIds(list);
​
}
    @Test
    public void  insert(){
        User user = new User(9L,"张明喆",20,"111@@qq.com");
        int insert = userMapper.insert(user);
        System.out.println(insert);
​
    }
​
    @Test
    public void update(){
        User user = new User(8L,"张明喆1",22,"111");
        user.setId(7L);
        userMapper.updateById(user);
    }
}
​

3.4 使用mp完成条件查询

 @Test
    public void page2(){
      QueryWrapper wrapper=new QueryWrapper<>();
        wrapper.gt("age",18);//gt表示>
        List list = userMapper.selectList(wrapper);
        list.forEach(System.out::println);
    }
//分页查询
    @Test
    public void page(){
        Page page=new Page<>(1,3);//1:当前第几页 3:每页显示条数
        userMapper.selectPage(page,null);//把查询分页的结果封装到page对象中
        System.out.println("当前页的数据"+page.getRecords());//获取当前页的数据
        System.out.println("当前的页数:"+page.getPages());
        System.out.println("所有数据日条数:"+page.getTotal());
    }
    

3.5 联表使用mp的分页对象

 @Autowired
    private EmpMapper empMapper;
    @Test
    public  void page2(){
        Page page=new Page<>(1,3);
        QueryWrapper wrapper=new QueryWrapper<>();
        wrapper.gt("sal",1000);
        empMapper.findPage(page,wrapper);
        System.out.println("当前页的数据"+page.getRecords());//获取当前页的数据
        System.out.println("当前的页数:"+page.getPages());
        System.out.println("所有数据日条数:"+page.getTotal());
    }

3----springboot整合swagger2

3.1 swagger2概述

编写和维护接口文档是每个程序员的职责,根据Swagger2可以快速帮助我们编写最新的API接口文档,再也不用担心开会前仍忙于整理各种资料了,间接提升了团队开发的沟通效率。

3.2 常用注解

@Api:修饰整个类,描述Controller的作用 @ApiOperation:描述一个类的一个方法,或者说一个接口 @ApiParam:单个参数描述 @ApiModel:用对象来接收参数 @ApiModelProperty:用对象接收参数时,描述对象的一个字段 @ApiImplicitParam:一个请求参数 @ApiImplicitParams:多个请求参数

3.3为什么用swagger2

为什么要用swagger,我的理由是方便,作为后端开放人员,最烦的事就是自己写接口文档和前端交互是不是需要各种参数很繁琐,项目集成swagger后就能自动生成接口文档,做到前端、后端联调接口文档的及时性和便利性。

1.支持 API 自动生成同步的在线文档:使用 Swagger 后可以直接通过代码生成文档,不再需要自己手动编写接口文档了,对程序员来说非常方便。 2.提供 Web 页面在线测试 API:有文档还不够,Swagger 生成的文档还支持在线测试。参数和格式都定好了,直接在界面上输入参数对应的值即可在线测试接口。

3.4如何使用接口文档swagger2

(1)引入依赖

 
        
            com.spring4all
            swagger-spring-boot-starter
            1.9.1.RELEASE
        
        
            com.github.xiaoymin
            swagger-bootstrap-ui
            1.7.8
        

(2)创建配置类-swagger2

@Configuration
@EnableSwagger2//开启swagger注解驱动
public class SwaggerConfig {
@Bean //把方法返回的数据对象 交于spring容器管理
    public Docket docket(){
    Docket docket = new Docket(DocumentationType.SWAGGER_2).groupName("QY163").apiInfo(getInfo()).select().apis(RequestHandlerSelectors.basePackage("com.sws.controller")).build();
    return docket;
}
private ApiInfo getInfo(){
    Contact contact = new Contact("张明喆", "http://www.baidu.com", "[email protected]");
    ApiInfo apiInfo = new ApiInfo("QY163心理健康测试", "QY163心理健康测试", "1.2.0", "http://www.jd.com",
            contact, "明哲科技有限公司", "http://www.mingzhe.com", new ArrayList());
    return apiInfo;
}
}
​

(3)访问swagger在线文档

http://ip:port/swagger-ui.html路径

Springboot mybatis-plus_第8张图片

http://ip:port/doc.html (**推荐**)

Springboot mybatis-plus_第9张图片

4---springboot整合定时器-quartz

在线Cron表达式生成器

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

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

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

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

4.1配置

(1)引入quartz依赖


            org.springframework.boot
            spring-boot-starter-quartz
        

(2)配置定时器任务

@Component//交给spring容器
public class QuarzConfig {
    @Scheduled(cron = "0/5 * * * * ? ")//每5秒触发一次
    public void show(){
        System.out.println("111");
    }
    @Autowired
    private Stundent1Mapper student1Mapper;
    @@Scheduled(cron = "0 0/5 * * * ?")//每5分钟触发一次
     public void show(){
        List student1 = student1Mapper.selectList(null);
        System.out.println(student1);
    }
}

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

@SpringBootApplication
@MapperScan("com.sws.mapper")
@EnableScheduling//开启定时任务
public class SpringbootMpApplication {
​
    public static void main(String[] args) {
        SpringApplication.run(SpringbootMpApplication.class, args);
    }
​
}

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