Springboot对数据库简单的增删(-)查

并非是那种传授并分享知识的,只想在个人博客上把自己学的东西记录下来,也希望我记录的东西对各位看官有帮助。


上一篇是记录数据的创建,这篇是上一篇的延续,上一篇目录结构大致是这样的

Springboot对数据库简单的增删(-)查

这一篇目录结构大致是这样的

Springboot对数据库简单的增删(-)查

细节部分就暂时不多说了,主要是CatDao
[html] view plain copy
 print?
  1. <span style="font-size:18px;"><strong>public interface CatDao extends CrudRepository<Cat, Integer> {  
  2.   
  3.   
  4.   
  5. }</strong></span>  

CatService
[html] view plain copy
 print?
  1. <span style="font-size:18px;"><strong>@Service  
  2. public class CatService {  
  3.   
  4.     @Resource  
  5.     private CatDao catDao;  
  6.   
  7.     //save,update ,delete 方法需要绑定事务.  
  8.     //使用@Transactional进行事务的绑定.  
  9.     //@param cat  
  10.   
  11.     //保存数据  
  12.     @Transactional  
  13.     public void save(Cat cat){  
  14.         catDao.save(cat);  
  15.     }  
  16.   
  17.     //删除数据  
  18.     @Transactional  
  19.     public void delete(int id){  
  20.         catDao.delete(id);  
  21.     }  
  22.   
  23.     //查询数据  
  24.     public Iterable<Cat> getAll(){  
  25.         return catDao.findAll();  
  26.     }  
  27.   
  28. }</strong></span>  

CatController
[html] view plain copy
 print?
  1. <span style="font-size:18px;"><strong>@RestController  
  2. @RequestMapping("/cat")  
  3. public class CatController {  
  4.   
  5.     @Resource  
  6.     private CatService catService;  
  7.   
  8.     //增加一条数据  
  9.     @RequestMapping("/save")  
  10.     public String save(){  
  11.         Cat cat = new Cat();  
  12.         cat.setCatName("Tom");  
  13.         cat.setCatAge(3);  
  14.         catService.save(cat);  
  15.         return "save OK";  
  16.     }  
  17.   
  18.     //删除下方相对应的ID  
  19.     @RequestMapping("/delete")  
  20.     public String delete(){  
  21.         catService.delete(1);  
  22.         return "delete OK";  
  23.     }  
  24.   
  25.     //显示所有的json数据(查看)  
  26.     @RequestMapping("/getAll")  
  27.     public Iterable<Cat> getAll(){  
  28.         return catService.getAll();  
  29.     }  
  30.   
  31. }</strong></span>  

在浏览器中输入http://localhost:8080/cat/save
Springboot对数据库简单的增删(-)查


因为controller中是写了死的数据-setCatName("Tom");,setCatAge(3);,加上表中的ID自增长,数据库表格中插入对应的数据为
Springboot对数据库简单的增删(-)查

输入http://localhost:8080/cat/delete,controller会自动删除指定的id-1,
Springboot对数据库简单的增删(-)查

Springboot对数据库简单的增删(-)查
连续插入五条数据,输入http://localhost:8080/cat/getAll,就能显示数据库中所有的json数据
Springboot对数据库简单的增删(-)查

修改的话在这里不好演示,就不写出了。
如上,在项目中把路径传到相对应的地方基本就能实现增删(-)查。

Springboot对数据库简单的增删改查演示完毕。

有源码才能更好的理解,百度云盘