2小时学会Spring Boot学习 - 数据库操作

Spring-Data-JPA 整合的是Hibernate

JPA(Java Persistence API)定义了一系列对象持久化的标准,目前实现这一规范的产品有Hibernate TopLink等

mysql启动命令  mysql.server start

1.添加依赖 pom.xml

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

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

2.修改配置 application.yml

datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/dbgirl
username: root
password: after
jpa:
hibernate:
ddl-auto: update  //create 会重新创建
show-sql: true

3.新建对象类,将自动对应生成数据库中属性字段
Girl.java

@Entity  //添加此注解
public class Girl {
@Id //id
@GeneratedValue //自增
private Integer id;
private String cupSize;
private Integer age;

public Girl() {
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getCupSize() {
return cupSize;
}

public void setCupSize(String cupSize) {
this.cupSize = cupSize;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}
}



4.新建接口文件
GirlReposistory.java
public interface GirlReposistory extends JpaRepository<Girl,Integer> {
//通过年龄查询
public List<Girl> findByAge(Integer age); //此接口为扩展接口, 注意命名规则 findBy[xxx]
}
5.新建controller类 并完成注解
@RestController
@RequestMapping(value = "/girls")
public class GirlController {

@Autowired
private GirlReposistory girlReposistory;

//获取女生列表
@GetMapping(value = "/list")
public List<Girl> girlList(){
return girlReposistory.findAll();
}

//添加一个女生
@PostMapping(value = "/add")
public Girl girlAdd(@RequestParam(value = "cupSize") String cupSize,
@RequestParam(value = "age") Integer age){
Girl girl = new Girl();
girl.setCupSize(cupSize);
girl.setAge(age);

return girlReposistory.save(girl);
}

//通过id查询一个女生
@GetMapping(value = "/search/{id}")
public Girl girlSearch(@PathVariable("id") Integer id){
return girlReposistory.findById(id).get();
}

//更新
@PutMapping(value = "/update/{id}")
public Girl girlUpdate(@PathVariable("id") Integer id,
@RequestParam("cupSize") String cupSize,
@RequestParam("age") Integer age){
Girl girl = new Girl();
girl.setId(id);
girl.setCupSize(cupSize);
girl.setAge(age);

return girlReposistory.save(girl);
}

//删除
@DeleteMapping(value = "/delete/{id}")
public void girlDelete(@PathVariable("id") Integer id){
girlReposistory.deleteById(id);
}

//通过年龄查询女生列表
@GetMapping(value = "/age/{age}")
public List<Girl> girlListByAge(@PathVariable("age") Integer age){
return girlReposistory.findByAge(age);
}

}











posted @ 2018-04-20 18:16  zhcnblog  阅读(170)  评论(0编辑  收藏  举报