mysql基本使用:https://blog.csdn.net/qq_35508033/article/details/71908310
http://www.ityouknow.com/springboot/2016/02/03/spring-boot-web.html
添加依赖、添加Mysql配置见上面网页
1、创建DAO(即直接与Mysql通信)
public interface UserRepository extends JpaRepository<User, Long> {
User findByUserName(String userName);
User findByUserNameOrEmail(String username, String email);
可以根据方法名来自动的生产SQL,比如findByUserName
会自动生产一个以 userName 为参数的查询方法,比如 findAlll
自动会查询表里面的所有数据,比如自动分页等等。(findAll
可以直接调用)
2、添加记录
在Controller中添加新方法实现往数据库中添加数据
/**
* 添加一个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来查询
创建StudentController
,只需使用findAll()
方法即可获取一个表的所有内容
@RestController
public class StudentController {
@Autowired
private StudentRepository studentRepository;
@RequestMapping("/getAllStudent")
public List<Student> getAllStudent(){
return studentRepository.findAll();
}
}
- 这里的
@Autowired
作用是自动装配,我们这里可以发现StudentRepository
并没有新建一个对象,这里可以直接使用@Autowired
4、查询某条记录
/**
* 根据ID获取student,接收ID参数
* @param id
* @return
*/
@GetMapping("/getStudent/{id}")
public Student getStudentById(@PathVariable("id") Integer id){
return studentRepository.findOne(id);
}
- 上面三个方法中使用的提交方式是不一样的,分别是
@PostMapping("/addStudent")
、@RequestMapping("/getAllStudent")
、@GetMapping("/getStudent/{id}")
三者区别是:
@GetMapping
是一个组合注解,是@RequestMapping(method = RequestMethod.GET)
的缩写。
@PostMapping
是一个组合注解,是@RequestMapping(method = RequestMethod.POST)
的缩写。 - 注意这里传入的参数中有一个
@PathVariable("id")
的注解,这个注解表示
5、更新某条记录
/**
* 根据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);
}