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

4

9

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.

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/"
}
Cress answered 26/7, 2017 at 8:57 Comment(3)
can you try --> @GeneratedValue(strategy = GenerationType.TABLE), this uses sequence table id assignmentPaludal
No, it does not work.Cress
@GeneratedValue(strategy = GenerationType.AUTO) will work, Ref: #4102949Paludal
C
14

It was my bad, I was calling foo(user.getId()) before saving the User object into the database. Takeaways from this: @GeneratedValue(strategy=GenerationType.IDENTITY) is the correct code and generates identical ids while saving to database1. And Long is not a problem. Thanks.

[1]: I am saving the object into the database by, something like: userRepository.save(user).

Cress answered 26/7, 2017 at 10:36 Comment(2)
It is always a good practice to post the correct code once you find the solution so that new learners who cannot understand jargons (like persisting in this case) can grasp it quickly.Presbytery
@Presbytery thanks, I did it long time ago. I edited as much as possible. Hope it is better now.Cress
L
1

Nothing is wrong WHETHER you do @GeneratedValue(strategy=GenerationType.IDENTITY) or @GeneratedValue(strategy=GenerationType.TABLE) in this particular problem. Any strategy works. ALL you have make sure is @PathVariable is used or not when you are passing id.

Landaulet answered 30/9, 2022 at 21:3 Comment(0)
S
0

To generate string uuid's for primary keys (as I assume you are trying to do) you can try the following code:

@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;
Sheasheaf answered 26/7, 2017 at 9:11 Comment(0)
U
0

Same issue encountered with findById() method while I was missing @PathVariable(value="id") ID id in getIdSpecificResult() method. This was a minor missing piece on my code. Reasons could be any though.

Unwitnessed answered 1/9, 2023 at 21:43 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.