JPA提供的 save()方法 进行增加和修改操作,实际就是saveOrUpdate
使用 save() 增加无问题,修改操作一直都变成了增加
Controller
package com.school.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.jayway.jsonpath.internal.function.Parameter;
import com.school.domain.Student;
import com.school.service.StuServiceImpl;
@Controller
@RestController
public class StuController {
@Autowired
private StuServiceImpl stuServiceImpl;
@RequestMapping("/Hello")
public String test(){
return "嘻嘻";
}
@RequestMapping("/main")
public ModelAndView show_view(Model model){
List<Student> stuList = stuServiceImpl.queryAll();
model.addAttribute("stuList", stuList);
return new ModelAndView("/index","showModel",model);
}
@RequestMapping("/addStu")
public ModelAndView add_stu(Student stu){
if(stuServiceImpl.insertStu(stu))
System.out.println("新增成功");
else
System.out.println("新增失败");
return new ModelAndView("redirect:/main");
}
@RequestMapping("/updateStu")
public ModelAndView update_stu(Student stu){
if(stuServiceImpl.updateStu(stu))
System.out.println("修改成功");
else
System.out.println("修改失败");
return new ModelAndView("redirect:/main");
}
}
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- stu 存入 model -->
<form th:action="@{~/updateStu}" method="POST">
<table>
<tr>
<td>姓名</td>
<td><input type="text" th:value="${stu.stuName}" name="stuName" /></td>
<td>年龄</td>
<td><input type="text" th:value="${stu.stuAge}" name="stuAge" /></td>
<td>电话</td>
<td><input type="text" th:value="${stu.telephone}" name="telephone" /></td>
</tr>
<tr>
<td><input type="submit" value="确认" style="margin-right: 25px;" /><input
type="button" value="取消" /></td>
</tr>
</table>
</form>
</body>
</html>
增加 修改 ,Service 层都是一样的代码
后来我发现只要请求时URL加入ID 操作就变成 update 了
修改:HTML页面
<form th:action="@{'~/updateStu/' + ${stu.id}}" method="POST">
Controller
@RequestMapping("/updateStu/{id}")
public ModelAndView update_stu(@RequestParam("id") Integer id,Student stu){
if(stuServiceImpl.updateStu(stu))
System.out.println("修改成功");
else
System.out.println("修改失败");
return new ModelAndView("redirect:/main");
}
这里controller 加不加 @RequestParam("id") Integer id 都有效果 可以省略