關於SpringBoot使用JPA的更新操作(save方法和原生SQL方法)


關於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方法進行數據更新


   
   
   
           
  1. //實體類
  2. @Entity
  3. public class Student extends JpaRepositoriesAutoConfiguration{
  4. private Integer id;
  5. private String name;
  6. private Integer age;
  7. //省略getter/setter方法和構造函數
  8. }

   
   
   
           
  1. //Controller類
  2. @RestController
  3. public class HelloController {
  4. @Autowired
  5. private StuRepository stuRepository;
  6. public void updateOne (@RequestParam("name") String name, @RequestParam("id") Integer id) {
  7. Student student = new Student();
  8. student.setName(name);
  9. student.setId(id);
  10. stuRepository.save(student); //實現數據更新
  11. }

使用該save方法進行更新時會發現,更新全部字段時會正常實現,可是在只更新部分字段時,會發現沒有更新的字段被置為null;

、使用原生SQL方法實現數據更新


   
   
   
           
  1. //原生SQL實現更新方法接口
  2. @Query(value = "update Studnet set name=?1 where id=?2 ", nativeQuery = true)
  3. @Modifying
  4. public void updateOne (String name,int id);

   
   
   
           
  1. //在這個方法中調用上面的接口
  2. @Transactional
  3. public String updateOne (@RequestParam("name") String name, @RequestParam("id") Integer id) {
  4. stuRepository.updateOne(name,id);
  5. return "更新成功";
  6. }

使用原生SQL方法來實現更新,就比較正常了,可以實現全部字段更新,同樣可以實現部分字段更新。

這里是增刪改查實例 
http://download.csdn.net/download/sinat_33889619/10035078 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM