【问题标题】:Error: The given id must not be null for GeneratedValue in JPA错误:JPA 中 GeneratedValue 的给定 id 不能为空
【发布时间】:2018-01-01 11:46:50
【问题描述】:

我的对象:

@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 不能为空。当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/"
}

【问题讨论】:

  • 你可以试试 --> @GeneratedValue(strategy = GenerationType.TABLE),这个使用sequence table id assignment
  • 不,它不起作用。
  • @GeneratedValue(strategy = GenerationType.AUTO) 将起作用,参考:stackoverflow.com/questions/4102449/…

标签: java rest jpa spring-boot spring-rest


【解决方案1】:

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

[1]:我将对象保存到数据库中,例如:userRepository.save(user)

【讨论】:

  • 一旦找到解决方案,贴出正确的代码总是一个好习惯,这样不懂行话的新学习者(比如在这种情况下坚持)可以快速掌握。
  • @Rahul 谢谢,我很久以前就做过了。我尽可能地编辑。希望现在好多了。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2017-06-27
    • 2012-02-23
    • 1970-01-01
    • 2018-11-10
    • 2014-01-07
    • 2020-10-25
    • 2020-07-15
    • 2021-11-19
    相关资源
    最近更新 更多