2小时上手Spring Boot 笔记

1. 使用idea建立Spring boot项目

  1. 在idea的菜单File-New-Project,选择Spring Initializr

  1. 填写项目名,其余所有默认

  1. 选择须要引入的包,这里暂时先引入web须要的包。后续根据本身实际状况在pom.xml增长。

  1. 项目保存的磁盘路径


2. application.yml文件

server:
 port: 8082 #端口号
 servlet:
 context-path: /girl #项目名

复制代码

2.1使用@value注解引入配置文件的参数

yml配置文件java

server:
 port: 8082 #端口号
 servlet:
 context-path: /girl #项目名
cupSize: B

复制代码

Controller代码mysql

@RestController
public class HelloController {

    @Value("${cupSize}")
    private String cupSize;

    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String say(){
        return "cupSize:"+cupSize;
    }
}
复制代码

页面输出效果web


2.2自引用配置文件中的参数

yml 配置文件spring

server:
 port: 8082 #端口号
 servlet:
 context-path: /girl #项目名
cupSize: B
age: 18
content : "cupSize: ${cupSize},age: ${age}"
复制代码

controller调用代码sql

@RestController
public class HelloController {
    

    @Value("${content}")
    private String content;

    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String say(){
        return content;
    }
}
复制代码

2.3经过@ConfigurationProperties写到一个类里

yml文件数据库

server:
 port: 8082 #端口号
 servlet:
 context-path: /girl #项目名
girl:
 cupSize: B
 age: 18

复制代码

引用的bean类app

  1. 使用@ConfigurationProperties须要引入包
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
复制代码
  1. 在bean打上注解@ConfigurationProperties
@Component
@ConfigurationProperties(prefix = "girl")
public class GirlProperties {

    private String cupSize;

    private Integer age;
复制代码

controller 注入调用代码ide

@RestController
public class HelloController {

    @Autowired
    private GirlProperties girlProperties;

    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String say(){
        return girlProperties.getCupSize();
    }
}

复制代码

使用spring.profiles.active 切换使用开发和生产环境的配置文件

spring:
 profiles:
 active: prod

复制代码


3. Controller 的使用

3.1 @RequestMapping的多url指向同一方法

映射两个或以上的url到同一个方法,可使用集合。函数

@RestController
public class HelloController {

    @Autowired
    private GirlProperties girlProperties;

    @RequestMapping(value = {"/hello","/hi"},method = RequestMethod.GET)
    public String say(){
        return girlProperties.getCupSize();
    }
}

复制代码

3.2 @RequestMapping 指向一个类

请求地址为:http://localhost:8082/girl/hello/sayspring-boot

@RestController
@RequestMapping("/hello")
public class HelloController {

    @Autowired
    private GirlProperties girlProperties;

    @RequestMapping(value = "/say",method = RequestMethod.POST)
    public String say(){
        return girlProperties.getCupSize();
    }
}

复制代码

3.3 @PathVariable的使用【 获取url 中的数值】

获取请求地址上定义的数值

@RequestMapping(value = "/say/{id}",method = RequestMethod.GET)
    public String say(@PathVariable("id") Integer id ){
        return "id:" +id;
    }

复制代码

请求地址:http://localhost:8082/girl/hello/say/100

输出效果:


3.4 @RequestParam 的使用【获取请求参数的值】

获取请求地址上?key=value 的参数值

@RequestMapping(value = "/say",method = RequestMethod.GET)
    public String say(@RequestParam("id") Integer myId ){
        return "id:" +myId;
    }

复制代码

请求地址:http://localhost:8082/girl/hello/say?id=666

输出效果:

  • 其他参数

    value 为默认参数

    required 表明参数是否必须

    defaultValue 参数默认值

    @RequestMapping(value = "/say",method = RequestMethod.GET)
        public String say(@RequestParam(value = "id", required = false,defaultValue = "0") Integer myId ){
            return "id:" +myId;
        }
    
    
    复制代码

4. 组合注解

  • @GetMapping
  • @PostMapping
  • @DeleteMapping
  • @PutMapping

简化的一种注解写法,代替了 @RequestMapping(value = "/say",method = RequestMethod.GET)

@GetMapping("/say")
    public String say(@RequestParam("id") Integer myId ){
        return "id:" +myId;
    }

复制代码

4.Spring Boot 链接数据库操做

4.1 配置

pom.xml引入JPA和mysql驱动包

  • 提醒:使用mysql5.x的版本,引入驱动包记得选择5.1x版本的数据库驱动包,不然会出现报错
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>


复制代码

application.yml配置内容

  • ddl-auto 参数,表明项目启动数据库表和实体的构建,通常用create 、update 、 none 的参数
    • create 表明每次启动从新删表重建
    • update 没有对应实体表则建立,补充的字段也会添加到表,但删除实体字段,不会删除表字段
    • none 不作任何处理
spring:
 profiles:
 active: dev
 datasource:
 driver-class-name: com.mysql.jdbc.Driver
 url: jdbc:mysql://127.0.0.1:3306/dbgirl
 username: root
 password: root
 jpa:
 hibernate:
 ddl-auto: update
 show-sql: true
    #JPA建立表默认引擎为 MyISAM,不支持事务回滚
    # 加上如下设置JPA建立表时引擎为支持事务的InnoDB,
 database-platform: org.hibernate.dialect.MySQL5InnoDBDialect


复制代码

实体类

  • 使用@Entity注解打到类上方表示实体表映射
  • @Id表明主键
  • @GeneratedValue 表明自增加
  • 别忘记必须有一个无参的构造函数
@Entity
public class Girl {

    @Id
    @GeneratedValue
    private Integer id;

    private String cupSize;

    private Integer age;

    private Integer height;

    public Girl() {}

复制代码

4.2 JPA查询列表【findAll()】

编写接口类继承 JpaRepository接口

  • JpaRepository<Girl,Integer> 第一个参数:实体类,第二个参数:主键类型
public interface GirlRepository extends JpaRepository<Girl,Integer> {
}

复制代码

controller调用

  • findAll() 查询全部
@RestController
public class GirlController {

    @Autowired
    private GirlRepository girlRepository ;

    /** * 查询全部女生列表 * @return */
    @GetMapping("/girls")
    public List<Girl> girlList(){
        return girlRepository.findAll();
    }
}


复制代码

输出效果:


4.3 JPA增长对象【save()】

controller调用

使用post方式添加一条数据,返回的是添加的这个对象

/** * 添加一个女生 * @param cupSize * @param age * @param height * @return */
    @PostMapping("/girls")
    public Girl girlAdd(@RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age, @RequestParam("height") Integer height){
        Girl girl = new Girl();
        girl.setCupSize(cupSize);
        girl.setAge(age);
        girl.setHeight(height);
        return girlRepository.save(girl);
    }

复制代码

输出效果:


4.4 JPA 经过id查询【findById(id).orElse(null)】

经过id查找单一对象findById(id).orElse(null),没有找到数据不会报错,并返回空,

//查询一个女生
    @GetMapping("/girls/{id}")
    public Girl girlFindOne(@PathVariable("id") Integer id){
        return girlRepository.findById(id).orElse(null);
    }

复制代码

4.5 JPA更新对象【save()】

//更新一个女生
    @PutMapping("/girls/{id}")
    public Girl girlUpdate(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age, @RequestParam("height") Integer height){
        Girl girl = new Girl();
        girl.setId(id);
        girl.setCupSize(cupSize);
        girl.setAge(age);
        girl.setHeight(height);
        return girlRepository.save(girl);
    }

复制代码

postman 使用put方法传递参数须要使用 x-www-form-urlencoded


4.6 JPA经过id删除对象【deleteById(id)】

controller 调用

// 删除一个女孩
    @DeleteMapping("/girls/{id}")
    public void girlDel(@PathVariable("id") Integer id){
        girlRepository.deleteById(id);
    }

复制代码

4.7 JPA经过字段其余条件查询

GirlRepository 扩展查询接口

  • 须要遵照规范,findBy字段
public interface GirlRepository extends JpaRepository<Girl,Integer> {

    public List<Girl> findByAge(Integer age);

}

复制代码

controller 调用

//经过年龄去查女生
    @GetMapping("/girls/age/{age}")
    public List<Girl> girlListByAge(@PathVariable("age") Integer age){
        return girlRepository.findByAge(age);
    }

复制代码

4.8 事务管理

在类上面打上@Service 和 @Component 都支持事务回滚

  • 注意事项【不然回滚不了】

    @Transactional回滚的方法必须为public

    mysql数据库引擎必须为InnoDB,特别检查对应的表是否InnoDB

Spring boot 2.0 的JPA 自动生成的表默认引擎为MyISAM,不支持事务回滚,在application.yml配置文件加上database-platform: org.hibernate.dialect.MySQL5InnoDBDialect

spring:
 profiles:
 active: dev
 datasource:
 driver-class-name: com.mysql.jdbc.Driver
 url: jdbc:mysql://127.0.0.1:3306/dbgirl
 username: root
 password: root
 jpa:
 hibernate:
 ddl-auto: update
 show-sql: true
    #JPA建立表默认引擎为 MyISAM,不支持事务回滚
    # 加上如下设置JPA建立表时引擎为支持事务的InnoDB,
 database-platform: org.hibernate.dialect.MySQL5InnoDBDialect


复制代码
  • 例子

Service 类代码

@Service
public class GirlService {

    @Autowired
    private  GirlRepository girlRepository;

    @Transactional
    public void insertTwo(){
        Girl girlA = new Girl();
        girlA.setCupSize("A");
        girlA.setAge(18);
        girlA.setHeight(155);
        girlRepository.save(girlA);

        Girl girlB = new Girl();
        girlB.setCupSize("BBBBB");
        girlB.setAge(16);
        girlB.setHeight(170);
        girlRepository.save(girlB);
    }
}

复制代码
相关文章
相关标签/搜索