【JPA】關於SpringBoot使用JPA的更新操作(save方法和原生SQL方法)
阿新 • • 發佈:2020-10-29
錯誤/異常: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