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