1. 使用idea创建Spring boot项目
-
在idea的菜单File-New-Project,选择Spring Initializr
- 填写项目名,其他全部默认
- 选择需要引入的包,这里暂时先引入web需要的包。后续根据自己实际情况在pom.xml增加。
-
项目保存的磁盘路径
2. application.yml文件
server:
port: 8082 #端口号
servlet:
context-path: /girl #项目名
复制代码
2.1使用@value注解引入配置文件的参数
yml配置文件
server:
port: 8082 #端口号
servlet:
context-path: /girl #项目名
cupSize: B
复制代码
Controller代码
@RestController
public class HelloController {
@Value("${cupSize}")
private String cupSize;
@RequestMapping(value = "/hello",method = RequestMethod.GET)
public String say(){
return "cupSize:"+cupSize;
}
}
复制代码
页面输出效果
2.2自引用配置文件中的参数
yml 配置文件
server:
port: 8082 #端口号
servlet:
context-path: /girl #项目名
cupSize: B
age: 18
content : "cupSize: ${cupSize},age: ${age}"
复制代码
controller调用代码
@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类
- 使用@ConfigurationProperties需要引入包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
复制代码
- 在bean打上注解@ConfigurationProperties
@Component
@ConfigurationProperties(prefix = "girl")
public class GirlProperties {
private String cupSize;
private Integer age;
复制代码
controller 注入调用代码
@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/say
@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);
}
}
复制代码