错误:对于 JPA 中的 GeneratedValue,给定的 id 不能为 null

Ani*_*kar 4 java rest jpa spring-boot spring-rest

我的对象:

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

  //more code
 }
Run Code Online (Sandbox Code Playgroud)

当我POST user JSON没有时uid,我收到错误,因为给定的 id 不能为 null。这不应该是这种情况,而uid应该由数据库生成。请指出我遗漏了什么。

JSON:

{
"email": "john@mail.com",
"name": "John Doe",
"phone": "98-765-4445"
}
Run Code Online (Sandbox Code Playgroud)

错误:

{
"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/"
}
Run Code Online (Sandbox Code Playgroud)

Ani*_*kar 6

这是我的错,我foo(user.getId())在坚持User对象之前打电话。无论如何,请远离此;@GeneratedValue(strategy=GenerationType.IDENTITY)是一个正确的代码,它在持久化时生成相同的 ID。而且Long不是问题。谢谢。

  • 找到解决方案后发布正确的代码始终是一个好习惯,以便无法理解行话的新学习者(例如在这种情况下坚持)可以快速掌握它。 (3认同)