SpringBoot基础知识点:创建、配置、JPA

前言

SpringBoot基础知识点:创建、配置、JPA
博客地址:芒果橙的个人博客 【http://mangocheng.com】

一、基础

1.特点

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

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

2.创建

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

3.配置信息

  1. application.properties,也可以是yml文件
# 服务器配置
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:指定配置文件

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

    • 属性读取@Value
     # application.yml定义一个age的变量
     age: 23
     name: 芒果橙
     description: 名字是${name}
    
    // Controller类中读取
    
    @Value("${name}")
    private String name;
    
    • 类读取@ConfigurationProperties
    person:
      age: 23
      name: 芒果橙
      description: 名字是${person.name}
    
    @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请求
@PostMappingpost请求
@RequestBody参数格式为json
@RequestMapping未指定,则GET/POST

示例

@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.属性名
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复杂动态查询条件
// 使用 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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

芒果-橙

谢谢啦!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值