简体   繁体   中英

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

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": "john@mail.com",
"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/"
}

It was my bad, I was calling foo(user.getId()) before persisting the User object. Anyways, take aways from this; @GeneratedValue(strategy=GenerationType.IDENTITY) is a correct code and it generates identical ids while persisting. And Long is not a problem. Thanks.

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;

Blockquote

make sure you type

without spell mistakes of properties as in entity class

it worked for me to solve this error

goodluck......

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM