java 错误:对于 JPA 中的 GeneratedValue,给定的 id 不能为 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45322118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error: The given id must not be null for GeneratedValue in JPA
提问by Anil Bhaskar
My object:
我的对象:
@Entity
@Table(name="user")
public class User {
@Id
@Column(name="uid")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
//more code
}
When I POST
user
JSON
without uid
, I am getting error as the given id must not be null. Which should not be the case while uid
should be generated by the database. Please point what am I missing.
当我POST
user
JSON
没有时uid
,我收到错误,因为给定的 id 不能为 null。这不应该是这种情况,而uid
应该由数据库生成。请指出我遗漏了什么。
JSON:
JSON:
{
"email": "[email protected]",
"name": "John Doe",
"phone": "98-765-4445"
}
Error:
错误:
{
"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/"
}
回答by Anil Bhaskar
It was my bad, I was calling foo(user.getId())
before persisting the User
object.
Anyways, take aways from this; @GeneratedValue(strategy=GenerationType.IDENTITY)
is a correct code and it generates identical ids while persisting. And Long
is not a problem. Thanks.
这是我的错,我foo(user.getId())
在坚持User
对象之前打电话。无论如何,请远离此;@GeneratedValue(strategy=GenerationType.IDENTITY)
是一个正确的代码,它在持久化时生成相同的 ID。而且Long
不是问题。谢谢。
回答by Mustafa
To generate string uuid's for primary keys (as I assume you are trying to do) you can try the following code:
要为主键生成字符串 uuid(我假设您正在尝试这样做),您可以尝试以下代码:
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;