Spring-Data-JPA 整合的是Hibernatejava
JPA(Java Persistence API)定義了一系列對象持久化的標準,目前實現這一規範的產品有Hibernate TopLink等mysql
mysql啓動命令 mysql.server startspring
1.添加依賴 pom.xmlsql
<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); }}