Spring JPA CURD 增删改查


控制器类

/**
 * 这是一个控制器类,相当于Servlet
 * @author wsh
 *
 */
@Controller //表示这是控制器类
public class PhoneController {
	
	@Autowired
	private PhoneRepository phoneService;	
	
	/**
	 * GET请求
	 * @return
	 */
	@RequestMapping("/") //请求路径是根路径
	public String root() {
		///return "redirect:/index"; //redirect表示重定向到/index
		return "admin/index";
	}

	@RequestMapping("/mb") //请求路径是根路径
	public String mb() {
		///return "redirect:/index"; //redirect表示重定向到/index
		return "admin/mb";
	}

	@RequestMapping("/add") //请求路径是根路径
	public String add() {
		///return "redirect:/index"; //redirect表示重定向到/index
		return "admin/add";
	}
	
	@RequestMapping("/list") //请求路径是根路径
	public String list(Model model) {
		model.addAttribute("phones", phoneService.findAll());
		return "admin/list";
	}
	
	@PostMapping("/phones/save")
	public String save(@Valid Phone phone,BindingResult result, Model model,RedirectAttributes redirectAttributes) {
		
		if(result.hasErrors()) {
			return "admin/add";
		}
		
		phoneService.save(phone);
		redirectAttributes.addFlashAttribute("msg",ConstantUtil.MSG_SAVED);
		return "redirect:/list";
	}
	
	@GetMapping("/edit/{id}") // {id}是占位符
	public String showUpdateForm(@PathVariable("id") long id, Model model) { // @PathVariable 路径变量
		Optional phone = phoneService.findById((int) id);
		model.addAttribute("phone",phone.get());
		return "admin/edit";
	}
	
	@PostMapping("/update/{id}")
	public String updateUser(@PathVariable("id") long id, @Valid Phone phone, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return "update-user";
		}
		phoneService.save(phone);
		return "redirect:/list";
	}
	
	@GetMapping("/delete/{id}")
	public String deleteUser(@PathVariable("id") long id, Model model) {
		phoneService.deleteById((int) id);
		return "redirect:/list";
	}
	
}

新增页面表单

查询所有 列表页面

ID 品牌 型号 颜色 操作 操作
修改 删除

修改单个页面