springBoot学习整理1

1.新建springboot项目

(1).可以在 spring项目搭建网站上去生成项目,如下图所示,可以选择maven版本跟gradle版本,输入项目名Group跟Artifact,点击generate Project 即可创建对应的springboot项目
在这里插入图片描述
(2).可以在idea上点击new,点击spring initializr,进入面板后就跟上面一样,输入,创建。
在这里插入图片描述

2.查看入口类application,也就是springBoot的启动类。

@SpringBootApplication
public class FirstAppDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(FirstAppDemoApplication.class, args);
	}

}

可以点击@SpringBootAppication注解

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {

除了前四个元注解以外,我们可以发现@SpringBootApplication注解中包含了@SpringBootCOnfiguration,@EnableAutoConfiguration以及常用的@ComponentScan注解

  1. SpringBootCOnfiguration,就是springmvc里面的Configuration注解,告诉Spring容器,这是一个配置类。
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
}
  1. EnableAutoConfiguration ,包含AutoConfigurationPackage和Import注解
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
   String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

   Class<?>[] exclude() default {};

   String[] excludeName() default {};
}
  • AutoConfigurationPackage中只有一个@Import注解,也就是导入一个Registrar注册类,Registrar的源码中大致意思应该是帮助spring容器注册包类的信息
@Import({Registrar.class})
public @interface AutoConfigurationPackage {
}

Registrar的注册代码如下

 AutoConfigurationPackages.register(registry, (new AutoConfigurationPackages.PackageImport(metadata)).getPackageName());
  • Import中导入的是我们在配置springcontext中的自动配置选择器,这里不详细说了,有兴趣的同学可以自己看下源码
  1. ComponentScan就是我们通常使用的组件扫描,这里是告诉spring,我们需要spring对我们自己自定义的过滤器跟排除过滤器进行扫描。因此,我们如果需要定义过滤器跟排除过滤器 ,则必须继承AutoConfigurationExcludeFilter跟TypeExcludeFilter类。

3.springBoot继承mybatis

1.在pom.xml中添加mybatis依赖

		<dependency>
			<groupId>mysql</groupId>
			<artifactId> mysql-connector-java</artifactId>
			<version> 5.1.30</version>
		</dependency>

2.在application.properties中添加数据源的配置以及mysql的配置

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=

mybatis.mapper-locations=classpath:/mapper/*.xml
mybatis.configuration.map-underscore-to-camel-case=true

spring.jpa.database=MYSQL
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

3.编写dao层:

public interface UserReposity{

    @Select("select * from user")
    List<User> findAll(User user);
    }

@Select注解并不能满足我们日常开发所需要的动态sql,因此,在这里可以使用@SelectProvider注解来进行动态sql的生成。

 @SelectProvider(type = UserDynaSql.class,method = "selectProvider")
    List<User> selectProvider(User user);

UserDynaSql类的代码如下所示:

package com.gc.firstappdemo.mybatis;

import com.gc.firstappdemo.domain.User;
import org.apache.ibatis.jdbc.SQL;

public class UserDynaSql {
    public String selectProvider(User user){
        return new SQL(){
            {
              SELECT("*");
              FROM("user");
              if(user.getUserName() != null){
                  WHERE("user_name = #{userName}");
              }
            }
        }.toString();
    }

    public String insertProvider(User user){
        return new SQL(){
            {
                INSERT_INTO("user");
                if(user.getUserName() != null){
                    VALUES("user_name","#{userName}");
                }
                if(user.getUserId() != null){
                    VALUES("user_id","#{userId}");
                }
            }
        }.toString();
    }
}

对应selectProdiver注解的还有其他增删改注解InsertProvider,UpdateProvider,DeleteProvier,用法都跟查询的注解一样。SQL继承的抽象类代码中,大家可以自己去看下。
4.在主程序中加入mapper扫描,告诉springBoot去扫描这个目录下所有的Mapper接口

@MapperScan("com.gc.firstappdemo.reposity")

数据组装
当不同表之间的数据存在一对多或者多对多的时候,我们需要对查询出来的数据进行组装。
在之前的springmvc继承mybatis中,这种工作是在mybatis映射的xml文件里面去做的,代码类似下面所示(property,column映射的是对象属性名跟表名):

    <resultMap id="workDetail" type="Work">
    <id property="id" column="id" />
        <result property="studentName" column="studentName"/>
        <result property="headImgUrl" column="headImgUrl"/>
        <result property="schoolName" column="schoolName"/>
        <result property="title" column="title"/>
        <result property="content" column="content"/>
        <result property="type" column="type"/>
        <result property="idNum" column="idNum"/>
        <collection property="workAttList" ofType="WorkAtt">
            <result property="originalImageUrl" column="originalImageUrl"/>
        </collection>
    </resultMap>

springBoot提供了@Results注解,可以对查询出来的结果进行组装。

   @Select("select * from user")
    @Results({
            @Result(id=true,column = "user_Id",property = "userId"),
            @Result(column = "user_Name",property = "userName"),
            @Result(column = "user_Password",property = "userPassword"),
            @Result(column = "user_id",property = "roles",
            many = @Many(select = "com.gc.firstappdemo.reposity.RoleReposity.listByUserId",
            fetchType = FetchType.EAGER)),})
    List<UserDto> findUserDtoAll(User user);

listByUserId的查询:

    @Select("select r.* from role r\n" +
            "join user_role ur on r.id = ur.role_id\n" +
            "join users u on u.user_id = ur.user_id\n" +
            "where u.user_id = #{userId}")
    List<Role> listByUserId(String userId);

userId这个参数是通过column中的“user_Id”传过去的。(如果这边没有查到roles里面的数据,可以查看mybatis.configuration.map-underscore-to-camel-case=true这个配置有没有加,这个配置是让mybatis自动转换驼峰命名法)

4.springBoot集成spring-data-jpa

pom中添加依赖

	<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
			<version>2.1.1.RELEASE</version>
	</dependency>

1.配置数据源,在application.properties配置中加入:

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=

mybatis.mapper-locations=classpath:/mapper/*.xml
mybatis.configuration.map-underscore-to-camel-case=true

spring.jpa.database=MYSQL
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
server.port=8080

2.在实体类中添加注解

  1. @Entity注解表明该类为实体类或者表
@Entity
public class User {
  1. @Id注解表示该字段为表的主键,@GeneratedValue表示生成主键的方式
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private String userId;
  1. @ManyToMany注解是用来映射该表(实体)与其他表(实体)多对多的关系,@JoinTable用来处理连接多对多关系映射,name字段为多对多关系的中间表
    jointColumns里面添加的是,中间表对应该实体(User)的主键;这个就相当于left joint user_roles on User.id = user_roles.user_id 中的对应关系
    inverseJoinColumns里面添加的是,中间表对应于映射表(Role)的主键;相当于left joint role on role.id = user_roles.role_id 中的对应关系
 @ManyToMany(
          targetEntity = Role.class,
          cascade = {CascadeType.PERSIST},
          fetch = FetchType.EAGER
  )
  @JoinTable(
          name = "user_role",
          joinColumns = {@JoinColumn(name = "user_id")},
          inverseJoinColumns = {@JoinColumn(name = "role_id")}
  )
  private Set<Role> roleSet;

3.dao层继承JpaRepository

public interface UserReposity2 extends JpaRepository<User,String> {}

@DynamicInsert,@DynamicUpdate可以直接实现mybatis中动态sql。

学习尚硅谷视频整理的文档 Spring Boot 1 1 Spring Boot入门 4 1.1 简介 4 1.2 微服务(martin fowler发表了一篇文章) 5 1.3 环境约束 7 1.4 第一个Spring Boot项目(jar):HelloWorld 8 1.5 入门案例详解 11 1.5.1 POM文件 11 1.5.2 主程序类,主入口类 12 1.6 使用Spring Initializer向导快速创建Spring Boot 16 2 Spring Boot配置 18 2.1 配置文件 18 2.2 YML语法 19 2.3 YML配置文件值获取 21 2.4 properties配置文件乱码问题 24 2.5 @ConfigurationProperties与@Value的区别 25 2.6 配置@PropertySource、@ImportResource、@Bean 27 2.7 配置文件占位符 30 2.8 Profile多环境支持 31 2.9 配置文件的加载位置 33 2.10 外部配置加载顺序 36 2.11 自动配置原理 37 2.12 @Conditional派生注解 41 3 Spring Boot与日志 42 3.1 日志框架分类和选择 42 3.2 SLF4j使用 43 3.3 其他日志框架统一转换成slf4j+logback 44 3.4 Spring Boot日志使用 45 3.5 Spring Boot默认配置 47 3.6 指定日志文件和日志Profile功能 52 3.7 切换日志框架(不使用SLF4j+LogBack) 54 4 Spring Boot与Web开发 55 4.1 Web开发简介 55 4.2 静态资源映射规则 56 4.3 引入Thymeleaf 60 4.4 Thymeleaf语法 61 4.5 SpringMVC自动配置原理 67 4.6 SpringBoot扩展与全面接管 70 4.7 如何修改SpringBoot的默认配置 72 4.8 【实验】CRUD操作 73 4.8.1 默认访问首页 73 4.8.2 登录页面国际化 74 4.8.3 登录 80 4.8.4 拦截器进行登录检查 81 4.8.5 实验要求(没按要求做,不想改了!) 82 4.8.6 CRUD-员工列表 83 4.8.7 CRUD-员工修改 86 4.8.8 CRUD-员工添加 87 4.8.9 CRUD-员工删除 88 4.9 错误处理原理&错误页面定制 90 4.10 配置嵌入式Servlet容器(springboot 1.50版本) 97 4.10.1 如何定制和修改Servelt容器的相关配置 97 4.10.2 注册servlet三大组件【servlet,filter,listener】 98 4.10.3 替换为其他嵌入式容器 102 4.10.4 嵌入式servlet容器自动配置原理 103 4.10.5 嵌入式servlet容器启动原理 103 4.11 使用外置的Servlet容器 104 4.11.1 步骤 104 4.11.2 原理 107 5 Spring Boot与Docker(虚拟化容器技术) 110 5.1 简介 110 5.2 核心概念 111 5.3 安装Docker 112 5.4 Docker常用命令&操作 113 5.5 安装MySQL示例 114 6 Spring Boot与数据访问 115 6.1 JDBC 115 6.1.1 实现 115 6.1.2 自动配置原理 116 6.2 整合Durid数据源 117 6.3 整合Mybatis 122 6.3.1 注解版 123 6.3.2 配置文件版 124 6.4 整合SpringData JPA 125 6.4.1 SpringData简介 125 6.4.2 整合 126 7 Spring Boot启动配置原理 128 7.1 启动流程(Springboot 1.50版本) 128 7.1.1 创建SpringApplication对象 129 7.1.2 运行run方法 130 7.1.3 编写事件监听机制 132 8 Spring Boot自定义starters 136 8.1 概述 136 8.2 步骤 137 9 更多Springboot整合示例 144 10 Spring Boot与缓存 145 10.1 JSR107缓存规范 145 10.2 Spring的缓存抽象 146 10.2.1 基本概念 146 10.2.2 整合项目 146 10.2.3 CacheEnable注解 148 10.2.4 Cache注解 150 10.3 整合redis 154 10.3.1 在Docker上安装redis 154 10.3.2 Redis的Template 154 10.3.3 整合(百度) 155
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值