spring boot API 完整版
如果看了不會的 請先看上一篇 步驟
如果程式碼有不懂得:q :15025525254
1.實體類定義:
@Entity
public class Girl {
@Id
@GeneratedValue
private Integer id ;
private String cupSize;
private Integer age;
// 省略setter和getter
}
2.實現對Gilr物件的操作介面:
@RestController
public class GirlController {
@Autowired
private GrilController girlRepository;
//private GirlServce girlServce;
@GetMapping(value = "/girls")
public List<Girl> girlList(){
return girlRepository.findAll();
}
@PostMapping(value = "/girls")
public Girl girlAdd ( @RequestParam ("cupSize")String cupSize, @RequestParam("age") Integer age){
Girl girl = new Girl();
girl.setCupSize(cupSize);
return girlRepository.save(girl);
}
//查詢
@GetMapping(value = "girls/{id}")
public Girl girlFindone(@PathVariable("id") Integer id){
return girlRepository.findOne(id);
}
//新增
@PostMapping(value = "girlsup")
public Girl up(@RequestBody Girl girl){
Girl girl1 = new Girl();
girl1.setCupSize(girl.getCupSize());
return girlRepository.save(girl1);
}
//刪除
@DeleteMapping(value = "girlsqq/")
public void girlUpdate(@RequestParam("id") Integer id){
girlRepository.delete(id);
}
// @PostMapping(value = "/girls/two")
// public void girlTwo(){
// girlServce.inserTwo();
// }
//修改
@PostMapping(value="update")
public Girl girl(@RequestBody Girl girl)
{
Girl girll =new Girl();
girl.setId(girl.getId());
girll.setCupSize(girl.getCupSize());
girll.setAge(girl.getAge());
return girlRepository.saveAndFlush(girll);
}
//分頁查詢
@PostMapping("/fenye")
public Page<Girl> page(){
int page = 0,size = 10; //這裡可以不寫死,留給前端的人寫。
Sort sort=new Sort(Sort.Direction.DESC,"id");
Pageable pageable=new PageRequest(page, size, sort);
return girlRepository.findAll(pageable);
}
}
3.下面針對該Controller編寫測試用例驗證正確性,具體如下。
package com.cy.coo.h;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface GrilController extends JpaRepository<Girl, Integer> ,PagingAndSortingRepository<Girl, Integer>, JpaSpecificationExecutor<Girl>{
public Page<Girl> findAll(Pageable pageable);
}
4. 溫馨提醒: 如過沒有配置yml或者依賴就會出現問題。