SpringBoot基础

CSDN博客地址:https://blog.csdn.net/qq_35893033/article/details/128401786

一、基础

1.特点

  • 化繁为简,简化配置
  • 备受关注
  • 微服务的入门级框架

    Microservice架构模式就是将整个Web应用组织为一系列小的Web服务。这些小的Web服务可以独立地编译及部署,并通过各自暴露的API接口相互通讯。它们彼此相互协作,作为一个整体为用户提供功能,却可以独立地进行扩展。

2.创建

  • 官网下载现成的SpringBoot demo
  • 通过maven构建(Pom.xml引入)

3.配置信息

  1. application.properties,也可以是yml文件
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    # 服务器配置
    server:
    port: 8080
    session-timeout: 30
    tomcat:
    uri-encoding: utf-8

    # spring配置
    spring:
    # 数据源配置
    datasource:
    # 需要加上时区
    url: jdbc:mysql://localhost:3306/dbName?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
    username: root
    password: xxx
    driver-class-name: com.mysql.cj.jdbc.Driver
    # JPA
    jpa:
    hibernate:
    ddl-auto: update # create每次运行都删除原有表创建新表,update不用每次创建新表
    show-sql: true # 打印sql语句
  1. 多环境配置

    不同环境可以使用不同的配置文件

    1)创建3个配置文件

    • application.yml:指定配置文件

    • application-dev.yml:开发环境

    • application-prod.yml:生产环境

    2)配置文件指定
    application.yml:指定配置文件

    1
    2
    3
    4
    # 指定使用哪个配置文件
    spring:
    profiles:
    active: dev/prod
  1. 在类/配置文件中进行调用

    • 属性读取@Value
    1
    2
    3
    4
    # application.yml定义一个age的变量
    age: 23
    name: 芒果橙
    description: 名字是${name}
    1
    2
    3
    4
    // Controller类中读取

    @Value("${name}")
    private String name;
    • 类读取@ConfigurationProperties
      1
      2
      3
      4
      person:
      age: 23
      name: 芒果橙
      description: 名字是${person.name}
      1
      2
      3
      4
      5
      6
      7
      @Component
      @ConfigurationProperties(prefix="person")
      public class PersonConfig{
      // 属性定义
      private String name;

      }

4.Controller的使用

  1. 相关注解
名称 说明
@Controller 处理HTTP请求
@RestController 返回json/xml。@ResponseBody+@Controller
@RequestMapping 配置URL映射
  1. 参数注解
名称 说明
@PathVariable 获取URL中的数据
@RequestParam 获取请求参数的值
@GetMapping 组合注解,get请求
@PostMapping post请求
@RequestBody 参数格式为json
@RequestMapping 未指定,则GET/POST

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@RestController
@RequestMapping("/bit")
public class BitOperationController {

@PostMapping("/recordBit")
public String recordBit(@RequestBody(required = true) TimeLineVO timeLineVO) {

return "success";
}

// url: xxx/fetchTimeLines/1000
@GetMapping("/fetchTimeLines/{id}")
public List<TimeLineVO> fetchTimeLines(@PathVariable(value = "id") String id) {

return null;
}

// url: xxx/say?id=23
@GetMapping("/say")
public String say(@RequestParam(value = "id")Integer id){

return "";
}
}

5.数据库操作 Spring-Data-Jpa

1. jpa

  • Java Persistence API,定义了一系列对象持久化的标准,目前实现这一规范的产品有hibernate、toplink

  • Sort对象: Sort sort = new Sort(Sort.Direction.ASC,”xh”);

2. RESTful api

  • 参考
  • 一套协议来规范多种形式的前端和同一个后台的交互方式

3. 定义查询方法

  • 根据属性名查询:findByNameLike

  • 使用jpa的NameQuery查询

    • 要使用全模糊查询,需要用Contains
  • 使用@Query查询

  • 自定义Repository实现

    参考来源《SpringBoot实战》,汪云飞著

示例

1
2
3
4
5
6
7
// 1.属性名
List<TDiary> findById(String id);
// 2.Query
@Query(
value = "select t.* from t_diary t where id in ?1", nativeQuery = true
)
List<Map<String,Object>> fetchDiaryById(List<String> ids);

4. 分页对象

  • Page对象 :分页

  • Example对象 :示例对象查询

  • ExampleMatcher

  • @Auditor:操作信息数据自动赋值

    • 实体类上注解
      • CreatedBy
      • LastModifiedBy
      • CreatedDate
      • LastModifiedDate
    • 设置默认用户
      • 定义类实现AuditorAware,通过重写方法可自定义其他属性值

5. SpecificationQuery复杂动态查询条件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// 使用 Specification 动态查询条件

// 可以简写lambda表达式
// 1.定义条件
Specification<Project> specification = new Specification<Project>() {
@Override
public Predicate toPredicate(Root<Project> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
// 1.查询条件箱
List<Predicate> predicateList = new ArrayList<>(3);
// 2.获取比较的属性
// Path groupIdPath = root.get("groupId");
Path name = root.get("name");
Path logo = root.get("logo");
// 3.组装单个条件,加入条件箱
Expression<Long> exp = root.get("groupId");
predicateList.add(exp.in(groupId));
if (!StringUtils.isEmpty(pageRequestVO.getName())) {
Predicate predicateName = criteriaBuilder.like(name,pageRequestVO.getName());
predicateList.add(predicateName);
}
if(!StringUtils.isEmpty(pageRequestVO.getLogo())){
Predicate predicateLogo = criteriaBuilder.equal(logo,pageRequestVO.getLogo());
predicateList.add(predicateLogo);
}
// 4.统一
Predicate predicate = criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));

return predicate;
}
};

Page<Project> page = repository.findAll(specification, pageable);
------ 本文结束感谢您的阅读 ------

本文标题:SpringBoot基础

文章作者:MangoCheng

发布时间:2022年12月21日 - 20:27:47

最后更新:2023年03月04日 - 08:46:30

原始链接:http://mangocheng.com/posts/a8fdf5f8.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。