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

37,960

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).

Share:
37,960
Anil Bhaskar
Author by

Anil Bhaskar

I am a Computer Science enthusiast. SOreadytohelp

Updated on November 30, 2021

Comments

  • Anil Bhaskar
    Anil Bhaskar over 2 years

    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/"
    }