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?
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);
What have I to do if I need another part of the created/updated object, except id
? (name
, date
for a User
entity).
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With