SpringBoot入門之簡單操作資料庫
阿新 • • 發佈:2019-02-17
1、新建一個介面類繼承JpaRepository
package com.tg; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; /** * Created by Administrator on 2017-10-11. */ public interface GirlRepository extends JpaRepository<Girl,Integer> { //通過年齡查詢 public List<Girl> findByAge(Integer age); }
2、Controller示例程式碼 (資料庫 增、刪、改、查)
package com.tg; import jdk.internal.org.objectweb.asm.tree.analysis.Value; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; /** * Created by Administrator on 2017-10-11. */ @RestController public class GirlController { @Autowired private GirlRepository girlRepository; @Autowired private GirlService girlService; /** * 查詢所有資料 * @return */ @GetMapping(value = "/girls") public List<Girl> girlList(){ return girlRepository.findAll(); } /** *新增一條資料 * @param age * @param name * @return */ @PostMapping(value = "/girls") public Girl girlAdd(@RequestParam("age")Integer age, @RequestParam("name") String name){ Girl girl =new Girl(); girl.setAge(age); girl.setName(name); return girlRepository.save(girl); } /** * 根據id查詢資料 * @param id * @return */ @GetMapping(value = "/girls/{id}") public Girl girlFindOne(@PathVariable("id")Integer id){ return girlRepository.findOne(id); } /** *更新資料 * @param id * @param age * @param name * @return */ @PutMapping(value = "/girls/{id}") public Girl girlUpdate(@PathVariable("id")Integer id, @RequestParam("age")Integer age, @RequestParam("name")String name){ Girl girl =new Girl(); girl.setAge(age); girl.setName(name); girl.setId(id); return girlRepository.save(girl); } /** * 根據id刪除 * @param id */ @DeleteMapping(value = "/girls/{id}") public void girlDelete(@PathVariable("id")Integer id){ girlRepository.delete(id); } /** * 通過年齡查詢 * @param age * @return */ @GetMapping(value = "/age/{age}") public List<Girl> girlListByAge(@PathVariable("age") Integer age){ return girlRepository.findByAge(age); } /*同時插入兩條資料*/ @PostMapping(value = "/two") public void girlTwo(){ girlService.insertTwo(); } }
3、Service示例程式碼
package com.tg; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; /** * Created by Administrator on 2017-10-11. */ @Service public class GirlService { @Autowired private GirlRepository girlRepository; @Transactional //事件註解 public void insertTwo(){ Girl girlF =new Girl(); girlF.setName("FEEEEWW"); girlF.setAge(16); girlRepository.save(girlF); Girl girlH =new Girl(); girlH.setName("H"); girlH.setAge(18); girlRepository.save(girlH); } }