0

I see in most of the coders save data(using spring data) as:

     savedEntity = repo.save(savedEntity);
     Long id = savedEntity.getId();

I am confused about why most of them assign back the returned value to the saved Entity while the following code also works exact(I have tested myself):

       repo.save(savedEntity);
       Long id = savedEntity.getId();

Did I miss some benefit of assigning back?

Yashasvi Raj Pant
  • 796
  • 2
  • 6
  • 25

2 Answers2

1

for example, let the entity be:

@Entity
public class SavedEntity {
 @Id
 private int id;

 private String name;

 //getter, setters, all arg-constructor, and no-arg constructor

}

Consider the object of SavedEntity is

SavedEntity entity = new SavedEntity(1,"abcd");

now for your first question,

SavedUser entity1 = repo.save(entity);
Long id = entity1.getId();

this entity1 object is the return object getting from the database, which means the above entity is saved in the database succesfully.

for the Second Question,

repo.save(entity);
Long id = entity.getId();//which you got it from SavedEntity entity = new SavedEntity(1,"abcd");

here the value of id is the integer you mentioned in place of id(the raw value).

Nayan
  • 271
  • 5
0

Most of the time the id (primary key) is generated automatically while storing the entity to the database using strategies like AUTO, Sequence etc. So as to fetch those id's or autogenerated primary key values we assign back the saved entity.

For example:

@Entity
public class Customer {

  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private Long id;
  private String firstName;
  private String lastName;

}

In this case you'll not pass the id externally but it will create a value for it automatically while storing the data to DB.

Sanket Singh
  • 844
  • 3
  • 20