[英]Error: The given id must not be null for GeneratedValue in JPA
我的object:
@Entity
@Table(name="user")
public class User {
@Id
@Column(name="uid")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
//more code
}
當我JSON
沒有uid
的情況下發布user
POST
時,出現錯誤,因為給定的 id 不能是 null 。 當uid
應該由數據庫生成時,情況不應如此。 請指出我錯過了什么。
JSON:
{
"email": "john@mail.com",
"name": "John Doe",
"phone": "98-765-4445"
}
錯誤:
{
"timestamp": 1501058952038,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.dao.InvalidDataAccessApiUsageException",
"message": "The given id must not be null!; nested exception is java.lang.IllegalArgumentException: The given id must not be null!",
"path": "/api/user/"
}
這是我的錯,我在持久化User
對象之前調用了foo(user.getId())
。 無論如何,請遠離此; @GeneratedValue(strategy=GenerationType.IDENTITY)
是一個正確的代碼,它在持久化時生成相同的 id。 而且Long
不是問題。 謝謝。
要為主鍵生成字符串 uuid(我假設您正在嘗試這樣做),您可以嘗試以下代碼:
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;
塊引用
確保您輸入
沒有實體類中的屬性拼寫錯誤
它為我解決了這個錯誤
祝好運......
在此特定問題中,無論您執行@GeneratedValue(strategy=GenerationType.IDENTITY)
還是@GeneratedValue(strategy=GenerationType.TABLE)
都沒有錯。 任何策略都有效。 當您傳遞id
時,您必須確保使用或不使用@PathVariable
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.