关于SpringBoot使用JPA的更新操作(save方法和原生SQL方法)
https://blog.csdn.net/weixin_38809962/article/details/81478635?spm=1001.2101.3001.6650.17&utm_medium=distribute.pc_relevant.none-task-blog-2~default~BlogCommendFromBaidu~Rate-17.pc_relevant_default&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2~default~BlogCommendFromBaidu~Rate-17.pc_relevant_default&utm_relevant_index=23
使用save时候先根据id把对象查询到 再更改具体某个属性的值再值save 会避免 部分属性更改时候 数据异常情况
自学SpringBoot遇到些问题,才有了这篇博客,里面可能有些错误,欢迎指教。
1、使用save方法进行数据更新
- //实体类
- @Entity
- public class Student extends JpaRepositoriesAutoConfiguration{
- private Integer id;
- private String name;
- private Integer age;
- //省略getter/setter方法和构造函数
- }
- //Controller类
- @RestController
- public class HelloController {
- @Autowired
- private StuRepository stuRepository;
- public void updateOne(@RequestParam("name") String name, @RequestParam("id") Integer id) {
- Student student = new Student();
- student.setName(name);
- student.setId(id);
- stuRepository.save(student);//实现数据更新
- }
使用该save方法进行更新时会发现,更新全部字段时会正常实现,可是在只更新部分字段时,会发现没有更新的字段被置为null;
、使用原生SQL方法实现数据更新
- //原生SQL实现更新方法接口
- @Query(value = "update Studnet set name=?1 where id=?2 ", nativeQuery = true)
- @Modifying
- public void updateOne(String name,int id);
- //在这个方法中调用上面的接口
- @Transactional
- public String updateOne(@RequestParam("name") String name, @RequestParam("id") Integer id) {
- stuRepository.updateOne(name,id);
- return "更新成功";
- }
使用原生SQL方法来实现更新,就比较正常了,可以实现全部字段更新,同样可以实现部分字段更新。
这里是增删改查实例
http://download.csdn.net/download/sinat_33889619/10035078