并非是那种传授并分享知识的,只想在个人博客上把自己学的东西记录下来,也希望我记录的东西对各位看官有帮助。
上一篇是记录数据的创建,这篇是上一篇的延续,上一篇目录结构大致是这样的
这一篇目录结构大致是这样的
细节部分就暂时不多说了,主要是CatDao
-
<span style="font-size:18px;"><strong>public interface CatDao extends CrudRepository<Cat, Integer> {
-
-
-
-
}</strong></span>
CatService
-
<span style="font-size:18px;"><strong>@Service
-
public class CatService {
-
-
@Resource
-
private CatDao catDao;
-
-
//save,update ,delete 方法需要绑定事务.
-
//使用@Transactional进行事务的绑定.
-
//@param cat
-
-
//保存数据
-
@Transactional
-
public void save(Cat cat){
-
catDao.save(cat);
-
}
-
-
//删除数据
-
@Transactional
-
public void delete(int id){
-
catDao.delete(id);
-
}
-
-
//查询数据
-
public Iterable<Cat> getAll(){
-
return catDao.findAll();
-
}
-
-
}</strong></span>
CatController
-
<span style="font-size:18px;"><strong>@RestController
-
@RequestMapping("/cat")
-
public class CatController {
-
-
@Resource
-
private CatService catService;
-
-
//增加一条数据
-
@RequestMapping("/save")
-
public String save(){
-
Cat cat = new Cat();
-
cat.setCatName("Tom");
-
cat.setCatAge(3);
-
catService.save(cat);
-
return "save OK";
-
}
-
-
//删除下方相对应的ID
-
@RequestMapping("/delete")
-
public String delete(){
-
catService.delete(1);
-
return "delete OK";
-
}
-
-
//显示所有的json数据(查看)
-
@RequestMapping("/getAll")
-
public Iterable<Cat> getAll(){
-
return catService.getAll();
-
}
-
-
}</strong></span>
在浏览器中输入http://localhost:8080/cat/save
因为controller中是写了死的数据-setCatName("Tom");,setCatAge(3);,加上表中的ID自增长,数据库表格中插入对应的数据为
输入http://localhost:8080/cat/delete,controller会自动删除指定的id-1,
连续插入五条数据,输入http://localhost:8080/cat/getAll,就能显示数据库中所有的json数据
修改的话在这里不好演示,就不写出了。
如上,在项目中把路径传到相对应的地方基本就能实现增删(-)查。
Springboot对数据库简单的增删改查演示完毕。
有源码才能更好的理解,百度云盘