錯誤/異常:org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save() 的解決方法
1、錯誤/異常圖
錯誤/異常描述:id的生成錯誤,在調用save()方法之前,必須先生成id。
2、解決方法
在對應的實體類的主鍵(id)的get方法上加上:@GeneratedValue(strategy = GenerationType.AUTO) 這句話即可。括號中的值,根據你使用的數據庫類型改。
自學SpringBoot遇到些問題,才有了這篇博客,里面可能有些錯誤,歡迎指教。
1、使用save方法進行數據更新
//實體類 @Entity public class Student extends JpaRepositoriesAutoConfiguration{ private Integer id; private String name; private Integer age; //省略getter/setter方法和構造函數 }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
//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);//實現數據更新 }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
使用該save方法進行更新時會發現,更新全部字段時會正常實現,可是在只更新部分字段時,會發現沒有更新的字段被置為null;
2、使用原生SQL方法實現數據更新
//省略實體類
- 1
//原生SQL實現更新方法接口 @Query(value = "update Studnet set name=?1 where id=?2 ", nativeQuery = true) @Modifying public void updateOne(String name,int id);
- 1
- 2
- 3
- 4
//在這個方法中調用上面的接口 @Transactional public String updateOne(@RequestParam("name") String name, @RequestParam("id") Integer id) { stuRepository.updateOne(name,id); return "更新成功"; }
- 1
- 2
- 3
- 4
- 5
- 6
使用原生SQL方法來實現更新,就比較正常了,可以實現全部字段更新,同樣可以實現部分字段更新。
這里是增刪改查實例
http://download.csdn.net/download/sinat_33889619/10035078