mysql基本使用:https://blog.csdn.net/qq_35508033/article/details/71908310
http://www.ityouknow.com/springboot/2016/02/03/spring-boot-web.html
添加依賴靠闭、添加Mysql配置見上面網(wǎng)頁
1、創(chuàng)建DAO(即直接與Mysql通信)
public interface UserRepository extends JpaRepository<User, Long> {
User findByUserName(String userName);
User findByUserNameOrEmail(String username, String email);
可以根據(jù)方法名來自動的生產(chǎn)SQL,比如findByUserName
會自動生產(chǎn)一個以 userName 為參數(shù)的查詢方法子眶,比如 findAlll
自動會查詢表里面的所有數(shù)據(jù)膝捞,比如自動分頁等等坦刀。(findAll
可以直接調(diào)用)
2、添加記錄
在Controller中添加新方法實現(xiàn)往數(shù)據(jù)庫中添加數(shù)據(jù)
/**
* 添加一個student,使用postMapping接收post請求
* @return
*/
@PostMapping("/addStudent")
public Student addStudent(@RequestParam("name") String name, @RequestParam("age") Integer age){
Student student=new Student();
student.setName(name);
student.setAge(age);
return studentRepository.save(student);
}
3绑警、查詢所有記錄
使用Controller來查詢
創(chuàng)建StudentController
求泰,只需使用findAll()
方法即可獲取一個表的所有內(nèi)容
@RestController
public class StudentController {
@Autowired
private StudentRepository studentRepository;
@RequestMapping("/getAllStudent")
public List<Student> getAllStudent(){
return studentRepository.findAll();
}
}
- 這里的
@Autowired
作用是自動裝配,我們這里可以發(fā)現(xiàn)StudentRepository
并沒有新建一個對象计盒,這里可以直接使用@Autowired
4渴频、查詢某條記錄
/**
* 根據(jù)ID獲取student,接收ID參數(shù)
* @param id
* @return
*/
@GetMapping("/getStudent/{id}")
public Student getStudentById(@PathVariable("id") Integer id){
return studentRepository.findOne(id);
}
- 上面三個方法中使用的提交方式是不一樣的北启,分別是
@PostMapping("/addStudent")
卜朗、@RequestMapping("/getAllStudent")
、@GetMapping("/getStudent/{id}")
三者區(qū)別是:
@GetMapping
是一個組合注解咕村,是@RequestMapping(method = RequestMethod.GET)
的縮寫场钉。
@PostMapping
是一個組合注解,是@RequestMapping(method = RequestMethod.POST)
的縮寫懈涛。 - 注意這里傳入的參數(shù)中有一個
@PathVariable("id")
的注解逛万,這個注解表示
5、更新某條記錄
/**
* 根據(jù)id更新student
* @param id
* @param name
* @param age
* @return
*/
@PutMapping("/updateStudent/{id}")
public Student updateStudent(@PathVariable("id") Integer id,@RequestParam("name") String name,@RequestParam("age") Integer age){
Student student=new Student();
student.setId(id);
student.setName(name);
student.setAge(age);
return studentRepository.save(student);
}