-
2018.7.16
今天上午开了一上午会,下午处理了一些事后开始正式进入工作并通过博客记录。也希望自己能够一直坚持通过这种方式记录自己的学习进度。
今天重新搭建了spring-boot-sample-mysql,上次通过代码实现了通过特定http访问对数据库进行增删改查分页等操作,同时大致实现了通过model.addAttribute()将数据库内容展示在网页上(为啥是大致,因为我的思路是通过循环得到一系列值,然后输出,实际上,当id长度突破我规定的长度或者id出现断号,这种思路就gg了。这种思路后续也许会通过某些语句去完善,但今天并没有完善,当前代码如下:)
@RequestMapping(value = "/viewAll",method = RequestMethod.GET) public String viewAll(Model model){ for(Long i=1L;i<=10;i++){ model.addAttribute("id"+i,personRepository.findAllById(i).getId()); model.addAttribute("name"+i,personRepository.findAllById(i).getName()); model.addAttribute("age"+i,personRepository.findAllById(i).getAge()); model.addAttribute("address"+i,personRepository.findAllById(i).getAddress()); } return "viewAll"; }
由于上次是在网上找到了合适的教程,使得自己顺利实现删除,实际上可能并不太理解。而今天我主要做的是,不通过教程实现多种方式的删除,如下代码实现的是:我希望通过对比用户输入的信息与数据库信息的一致性来决定用户是否有删除权。
@RequestMapping(value = "/delete",method = RequestMethod.GET)
public ModelAndView delete(@RequestParam(value = "id") Long id,
@RequestParam(value = "name") String name,
@RequestParam(value = "age") Integer age,
@RequestParam(value = "address") String address) {
logger.info("delete 开始");Person p = new Person(id, name, age, address);
Person p1 = new Person();
p1.setId(id);
p1.setName(personRepository.findAllById(id).getName());
p1.setAge(personRepository.findAllById(id).getAge());
p1.setAddress(personRepository.findAllById(id).getAddress());if (p.getName().equals(p1.getName()) && p.getAge().equals(p1.getAge()) && p.getAddress().equals(p1.getAddress())) {
personRepository.delete(p);
return new ModelAndView(new RedirectView("viewAll"));
} else {
return new ModelAndView(new RedirectView("error"));
//return "输入信息有误!";
}logger.info("delete 开始");
}
实现过程比较坎坷,学到了很多,也犯了一些低级错误以及部分困扰,比如:
- "==" 与 "equals" :"==" 用来匹配地址值,"equals" 用来匹配字符串。
- 返回值类型不统一的将就:对比正确则使用ModelAndView去返回,而对比失败也使用了ModelAndView;尝试通过写String错误返回方法,并通过调用该方法返回String值,这个尝试也是不可行的,好像这个尝试也算个低级错误。
- 当数据库中有null值时,比如Person(1,zk,16,null),就无法通过该方式进行删除了。原因是equals的参数不能是null。解决方法还是只能想到加if语句进行判断。