Error: The given id must not be null for GeneratedValue in JPA

Error: The given id must not be null for GeneratedValue in JPA

我的对象:

@Entity
@Table(name="user")
public class User {
    @Id
    @Column(name="uid")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

  //more code
 }

当我 POST user JSON 没有 uid 时,我收到错误消息,因为 给定的 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/"
}

要为主键生成字符串 uuid(正如我假设您正在尝试做的那样),您可以尝试以下代码:

@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;

这是我的错,我在将 User 对象保存到数据库之前调用了 foo(user.getId())。 从中得出的结论是:@GeneratedValue(strategy=GenerationType.IDENTITY) 是正确的代码并在保存到数据库时生成相同的 ID1。而 Long 不是问题。谢谢。

[1]:我通过以下方式将对象保存到数据库中:userRepository.save(user).