Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DAO / repository: Good practice return value after insert / update

Although probably a trivial question, I've always wondered about this.

Usually, after insertion into the db, it seems common practice to return the id of the business entity.

@Override
public Long createUser(UserEntity user) {
    em.merge(user); 
    em.flush(); 

    return user.getId(); 
}

Is there a convincing reason for returning the id instead of the business object reference itself?

Similarly, I've seen update return void, while it might just as well be an id / User.

If I were to write a DAO / Repository for others to use, what would be the advised return value (if any), and why?

like image 935
html_programmer Avatar asked Jul 05 '16 10:07

html_programmer


Video Answer


3 Answers

Why not return the whole instance if it has been created/updated successfully? The same what Spring Data do,

<S extends T> S save(S entity);
<S extends T> Iterable<S> save(Iterable<S> entities);
  1. What have I to do if I need another part of the created/updated object, except id? (name, date for a User entity).

  2. Why does id return if there are a few fields that exactly characterise an instance (a composite primary key)?

There is no difficulty to return the whole object (nothing is "overhead" here as mentioned by @Danny Fonk), but it may save much your time in the future.

like image 101
Andrew Tobilko Avatar answered Sep 29 '22 15:09

Andrew Tobilko


As per my experience , In insertion process return the id to the business entity is good practice because that id might be use full to continue the business process as it is newly entered record , moreover for the update process we fetch the entity before we update the record so that means we already got the id , so it's not necessary to return the id

like image 45
IZI_SL Avatar answered Sep 29 '22 14:09

IZI_SL


I also think that returning the ID in general is good if not even best practive. Or you can also return the whole object but this is kinda "overhead" if you don't need to work with it anymore after creation.

At updating/altering an object in the database we always return the object itself or most likely just a boolean wether the update was succesfull or not since we already have the object.

like image 25
Danny Fonk Avatar answered Sep 29 '22 16:09

Danny Fonk