Search code examples
jpaspring-mvcspring-dataspring-data-jpa

Spring data jpa save can not get id


My entity id is generated, and it was working fine when I use DAO instead of Spring data JPA.

@Id
@Column(name = TABLE_COLUM_NAME_ID)
@GeneratedValue
private int id;

Now I have starting to use Spring data JPA, and after I call repository.save(myboject), or repository.saveAndFlush(myobject), I call myobject.getId(). But the id is never populated.

I searched my database and the object is in the database and the id is correct. Does anyone know why the id is not set after i called save()? I have no issue when I use entitymanager.save().


Solution

  • Try this like

    myboject = repository.save(myboject);
    repository.flush();
    

    Then after call to getId();