spring boot,sping data jpa 接口 CurdRepository save()函数问题

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 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





Insert title here


    
	
姓名 年龄 电话

 

增加 修改 ,Service 层都是一样的代码

 

后来我发现只要请求时URL加入ID 操作就变成 update 了

修改:HTML页面

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 都有效果 可以省略

 

你可能感兴趣的:(spring boot,sping data jpa 接口 CurdRepository save()函数问题)