johnygold | 1 Apr 16:21
Picon
Favicon

Should entities save/update themselves?

Hi,
In typical DDD application Services call entities methods to change 
some business state (for example, productService calls 
Product.changeName() to change the product name) and in the end those 
changes should be persisted to some data source. There are two 
options to persist the data (with respect to whom is responsible for 
that): 
(1) The service is calling some data provider to save/update the 
entity after all the changes

(2) The entity itself is being injected with some data provider class 
(via interface, e.g. IDao) and the entity can save/update itself: 
myDAO.update(this).

The first method make the entity completly agnostic to data sources. 
However the second method allows the entity to perform tomic 
operations and to decide when persisting should take place.

Which of the aforementioned methods do you prefer? is there any 
common/recommended way for that pattern?

Thanks.

------------------------------------

Freezing | 1 Apr 19:44
Picon

Re: Should entities save/update themselves?

If you wish to reuse your domain model across different application boundaries , it is usually not advisable to leave the decision of persistence to your entitities.

SC

2008/4/1, johnygold <johnygold <at> yahoo.com>:

Hi,
In typical DDD application Services call entities methods to change
some business state (for example, productService calls
Product.changeName() to change the product name) and in the end those
changes should be persisted to some data source. There are two
options to persist the data (with respect to whom is responsible for
that):
(1) The service is calling some data provider to save/update the
entity after all the changes

(2) The entity itself is being injected with some data provider class
(via interface, e.g. IDao) and the entity can save/update itself:
myDAO.update(this).

The first method make the entity completly agnostic to data sources.
However the second method allows the entity to perform tomic
operations and to decide when persisting should take place.

Which of the aforementioned methods do you prefer? is there any
common/recommended way for that pattern?

Thanks.


__._,_.___

Your email settings: Individual Email|Traditional
Change settings via the Web (Yahoo! ID required)
Change settings via email: Switch delivery to Daily Digest | Switch to Fully Featured
Visit Your Group | Yahoo! Groups Terms of Use | Unsubscribe

__,_._,___
Rickard Öberg | 2 Apr 02:42
Picon
Gravatar

Re: Should entities save/update themselves?

johnygold wrote:
> In typical DDD application Services call entities methods to change
> some business state (for example, productService calls
> Product.changeName() to change the product name) and in the end those
> changes should be persisted to some data source. There are two
> options to persist the data (with respect to whom is responsible for
> that):
> (1) The service is calling some data provider to save/update the
> entity after all the changes
> 
> (2) The entity itself is being injected with some data provider class
> (via interface, e.g. IDao) and the entity can save/update itself:
> myDAO.update(this).
> 
> The first method make the entity completly agnostic to data sources.
> However the second method allows the entity to perform tomic
> operations and to decide when persisting should take place.
> 
> Which of the aforementioned methods do you prefer? is there any
> common/recommended way for that pattern?

Here's how we do it in Qi4j(.org):
All work on Entities is done through a UnitOfWork. When a client begins 
a process it creates a UnitOfWork, which it then can use to lookup 
entities by id or through queries. All returned Entities are managed and 
registered in the UoW. When the client process is complete (and it may 
be a "long" or "short" transaction) it calls complete() on the UoW at 
which point the UoW will sync the state down to the underlying store(s), 
potentially using Transactions.

This way the Entities themselves are unaware of persistence, and it is 
the client who is responsible for properly delineating where a process 
begins and ends. Since all access is done through UoW's it also becomes 
trivial to implement the store as a batch interface (i.e. it deals with 
creating/updating/removing lists of objects rather than single ones), 
which potentially improves performance.

Sample code:
// Create new UoW
UnitOfWork uow = uowFactory.newUnitOfWork();

// Get reference to Entity
Order order = uow.getReference("1234",Order.class);

// Update state, through Property object
order.comment().set("Customer wants it to be sent to home address");

// UoW is done, sync with underlying store(s)
uow.complete();

/Rickard

------------------------------------

Alasdair Gilmour | 2 Apr 11:30
Picon

Re: Should entities save/update themselves?

Given just the two options, I would definitely go for no. (1) as I think entities should ideally know nothing about persistence. 
 
However, if you use an ORM solution like Hibernate then this can be made even more transparent: When the ORM loads entities from the database, it keeps track of them in a Session and stores a snapshot of their initial state. The entities then get manipulated in the normal way by the business logic. When a particular transaction completes, the system compares all of the objects in the Session with their initial state to detect changes, and issues database calls to make those changes persistent automatically. In the case where you are creating brand new entities, if you are attaching them to other entities which are already in the Session, then the ORM can automatically "cascade" persistence to these too, without requiring any explicit call to a save(). Sup plementing this with a mechanism for declarative transaction demarcation, you don't even have to code explicit transaction begins/commits/rollbacks - you can arrange for a framework to transparently intercept calls to your service methods and decorate them with the necessary begin/commit logic.
 
Using this kind of arrangement you don't need to have your entities aware of the data providers, and for the most part, you don't have to make save/update calls from your services either. This makes persistence concerns about as non-intrusive as they can be, and seems to work well in practice.
 
Al
 
> Hi,
> In typical DDD application Services call entities methods to change
> some business state (for example, productService calls
> Product.changeName() to change the product name) and in the end those
> changes should be persisted to some data source. There are two
> options to persist the data (with respect to whom is responsible for
> that):
> (1) The service is calling some data provider to save/update the
> entity after all the changes
>
> (2) The entity itself is being injected with some data provider class
> (via interface, e.g. IDao) and the entity can save/update itself:
> myDAO.update(this).
>
> The first method make the entity completly agnostic to data sources.
> However the second method allows the entity to perform tomic
> operations and to decide when persisting should take place.
>
> Which of the aforementioned methods do you prefer? is there any
> common/recommended way for that pattern?
>
> Thanks.
__._,_.___

Your email settings: Individual Email|Traditional
Change settings via the Web (Yahoo! ID required)
Change settings via email: Switch delivery to Daily Digest | Switch to Fully Featured
Visit Your Group | Yahoo! Groups Terms of Use | Unsubscribe

__,_._,___
johnygold | 2 Apr 11:33
Picon
Favicon

Re: Should entities save/update themselves?

Thanks for your replies, i'm still not sure why entities should be 
unaware of the need to save/commit themself after some change.
From the rational point, it seems logical to me for an entity to call
"save()" on some provider when some change is finished (for example
when product entity finish to change its name, it calls IDao.save. 
This provider is just an interface for the entity which represent a 
place to commit transactions. The interface IDao might do nothing 
when reusing the entity in another application boundary, for example 
on application without DB.

Moreover, there are situation when aggregate entity must persist 
changses during some process (not in the end) , otherwise the 
operation won't be atomic. For example, when aggregate entity is 
performing changes in collection of childs it might be neccesary to 
save changes after each single change.

Will be glad to hear your opinion.

--- In domaindrivendesign <at> yahoogroups.com, Rickard �berg 
<rickardoberg@...> wrote:
>
> johnygold wrote:
> > In typical DDD application Services call entities methods to 
change
> > some business state (for example, productService calls
> > Product.changeName() to change the product name) and in the end 
those
> > changes should be persisted to some data source. There are two
> > options to persist the data (with respect to whom is responsible 
for
> > that):
> > (1) The service is calling some data provider to save/update the
> > entity after all the changes
> > 
> > (2) The entity itself is being injected with some data provider 
class
> > (via interface, e.g. IDao) and the entity can save/update itself:
> > myDAO.update(this).
> > 
> > The first method make the entity completly agnostic to data 
sources.
> > However the second method allows the entity to perform tomic
> > operations and to decide when persisting should take place.
> > 
> > Which of the aforementioned methods do you prefer? is there any
> > common/recommended way for that pattern?
> 
> Here's how we do it in Qi4j(.org):
> All work on Entities is done through a UnitOfWork. When a client 
begins 
> a process it creates a UnitOfWork, which it then can use to lookup 
> entities by id or through queries. All returned Entities are 
managed and 
> registered in the UoW. When the client process is complete (and it 
may 
> be a "long" or "short" transaction) it calls complete() on the UoW 
at 
> which point the UoW will sync the state down to the underlying store
(s), 
> potentially using Transactions.
> 
> This way the Entities themselves are unaware of persistence, and it 
is 
> the client who is responsible for properly delineating where a 
process 
> begins and ends. Since all access is done through UoW's it also 
becomes 
> trivial to implement the store as a batch interface (i.e. it deals 
with 
> creating/updating/removing lists of objects rather than single 
ones), 
> which potentially improves performance.
> 
> Sample code:
> // Create new UoW
> UnitOfWork uow = uowFactory.newUnitOfWork();
> 
> // Get reference to Entity
> Order order = uow.getReference("1234",Order.class);
> 
> // Update state, through Property object
> order.comment().set("Customer wants it to be sent to home address");
> 
> // UoW is done, sync with underlying store(s)
> uow.complete();
> 
> /Rickard
>

------------------------------------

Ertugrul Uysal | 2 Apr 11:45
Picon
Favicon

Re: Should entities save/update themselves?

Would this work if we made manual updates to the database either with SQL or through stored procedures? In practice we can not totally avoid them for a variety of reasons. We sometimes need information from objects updated this way within a session. Can you come up with designs that totally avoid these or do you have some tricks you 'd like to share?

----- Original Message ----
From: Alasdair Gilmour <alasdairg <at> gmail.com>
To: domaindrivendesign <at> yaho ogroups.com
Sent: Wednesday, April 2, 2008 12:30:07 PM
Subject: Re: [domaindrivendesign] Should entities save/update themselves?

Given just the two options, I would definitely go for no. (1) as I think entities should ideally know nothing about persistence. 
 
However, if you use an ORM solution like Hibernate then this can be made even more transparent: When the ORM loads entities from the database, it keeps track of them in a Session and stores a snapshot of their initial state. The entities then get manipulated in the normal way by the business logic. When a particular transaction completes, the system compares all of the objects in the Session with their initial state to detect changes, and issues database calls to make those changes persistent automatically. In the case where you are creating brand new entities, if you are attaching them to other entities which are already in the Session, then the ORM can automatically "cascade" persistence to these too, without requiring any explicit call to a save(). Supplementing this with a mechanism for declarative transaction demarcation, you don't even have to code explicit transaction begins/commits/rollbacks - you can arrange for a framework to transparently intercept calls to your service methods and decorate them with the necessary begin/commit logic.
 
Using this kind of arrangement you don't need to have your entities aware of the data providers, and for the most part, you don't have to make save/update calls from your services either. This makes persistence concerns about as non-intrusive as they can be, and seems to work well in practice.
 
Al
 
> Hi,
> In typical DDD application Services call entities methods to change
> some business state (for example, productService calls
> Product.changeName() to change the product name) and in the end those
> changes should be persisted to some data source. There are two
> options to persist the data (with respect to whom is responsible for
> that):
> (1) The service is calling some data provider to save/update the
> entity after all the changes
>
> (2) The entity itself is being injected with some data provider class
> (via interface, e.g. IDao) and the entity can save/update itself:
> myDAO.update(this).
>
> The first method make the entity completly agnostic to data sources.
> However the second method allows the entity to perform tomic
> operations and to decide when persisting should take place.
>
> Which of the aforementioned methods do you prefer? is there any
> common/recommended way for that pattern?
>
> Thanks.


You rock. That's why Blockbuster's offering you one month of Blockbuster Total Access, No Cost. __._,_.___

Your email settings: Individual Email|Traditional
Change settings via the Web (Yahoo! ID required)
Change settings via email: Switch delivery to Daily Digest | Switch to Fully Featured
Visit Your Group | Yahoo! Groups Terms of Use | Unsubscribe

__,_._,___
David Perfors | 2 Apr 11:47
Picon

Re: Re: Should entities save/update themselves?

When entities are changed, most of the time a lot of external things
should change as well (like the database or the GUI). Therefore I
always use events to say that something is changed. The problem here
is to register the event handler to the entities on the right time..

For me the reason not to call a save/commit is that a database or the
database layer could change. When this happens, the domain should be
changed as well.

David

On Wed, Apr 2, 2008 at 11:33 AM, johnygold <johnygold <at> yahoo.com> wrote:
> Thanks for your replies, i'm still not sure why entities should be
>  unaware of the need to save/commit themself after some change.
>  From the rational point, it seems logical to me for an entity to call
>  "save()" on some provider when some change is finished (for example
>  when product entity finish to change its name, it calls IDao.save.
>  This provider is just an interface for the entity which represent a
>  place to commit transactions. The interface IDao might do nothing
>  when reusing the entity in another application boundary, for example
>  on application without DB.
>
>  Moreover, there are situation when aggregate entity must persist
>  changses during some process (not in the end) , otherwise the
>  operation won't be atomic. For example, when aggregate entity is
>  performing changes in collection of childs it might be neccesary to
>  save changes after each single change.
>
>  Will be glad to hear your opinion.
>
>  --- In domaindrivendesign <at> yahoogroups.com, Rickard �berg
>
>
> <rickardoberg@...> wrote:
>  >
>  > johnygold wrote:
>  > > In typical DDD application Services call entities methods to
>  change
>  > > some business state (for example, productService calls
>  > > Product.changeName() to change the product name) and in the end
>  those
>  > > changes should be persisted to some data source. There are two
>  > > options to persist the data (with respect to whom is responsible
>  for
>  > > that):
>  > > (1) The service is calling some data provider to save/update the
>  > > entity after all the changes
>  > >
>  > > (2) The entity itself is being injected with some data provider
>  class
>  > > (via interface, e.g. IDao) and the entity can save/update itself:
>  > > myDAO.update(this).
>  > >
>  > > The first method make the entity completly agnostic to data
>  sources.
>  > > However the second method allows the entity to perform tomic
>  > > operations and to decide when persisting should take place.
>  > >
>  > > Which of the aforementioned methods do you prefer? is there any
>  > > common/recommended way for that pattern?
>  >
>  > Here's how we do it in Qi4j(.org):
>  > All work on Entities is done through a UnitOfWork. When a client
>  begins
>  > a process it creates a UnitOfWork, which it then can use to lookup
>  > entities by id or through queries. All returned Entities are
>  managed and
>  > registered in the UoW. When the client process is complete (and it
>  may
>  > be a "long" or "short" transaction) it calls complete() on the UoW
>  at
>  > which point the UoW will sync the state down to the underlying store
>  (s),
>  > potentially using Transactions.
>  >
>  > This way the Entities themselves are unaware of persistence, and it
>  is
>  > the client who is responsible for properly delineating where a
>  process
>  > begins and ends. Since all access is done through UoW's it also
>  becomes
>  > trivial to implement the store as a batch interface (i.e. it deals
>  with
>  > creating/updating/removing lists of objects rather than single
>  ones),
>  > which potentially improves performance.
>  >
>  > Sample code:
>  > // Create new UoW
>  > UnitOfWork uow = uowFactory.newUnitOfWork();
>  >
>  > // Get reference to Entity
>  > Order order = uow.getReference("1234",Order.class);
>  >
>  > // Update state, through Property object
>  > order.comment().set("Customer wants it to be sent to home address");
>  >
>  > // UoW is done, sync with underlying store(s)
>  > uow.complete();
>  >
>  > /Rickard
>  >
>
>
>
>  ------------------------------------
>
>  Yahoo! Groups Links
>
>
>
>

------------------------------------

Yahoo! Groups Links

<*> To visit your group on the web, go to:
    http://groups.yahoo.com/group/domaindrivendesign/

<*> Your email settings:
    Individual Email | Traditional

<*> To change settings online go to:
    http://groups.yahoo.com/group/domaindrivendesign/join
    (Yahoo! ID required)

<*> To change settings via email:
    mailto:domaindrivendesign-digest <at> yahoogroups.com 
    mailto:domaindrivendesign-fullfeatured <at> yahoogroups.com

<*> To unsubscribe from this group, send an email to:
    domaindrivendesign-unsubscribe <at> yahoogroups.com

<*> Your use of Yahoo! Groups is subject to:
    http://docs.yahoo.com/info/terms/

Alasdair Gilmour | 2 Apr 13:14
Picon

Re: Re: Should entities save/update themselves?

IMHO, its just down to separation of concerns and the Single Responsibility Principle: A Product entity represents a specific business concept in the domain. Saving an object's state to the database is a completely orthogonal responsibility that is nothing to do with "being a Product", so it doesn't conceptually belong within the Product entity.
 
Moreover, within an application, an entity can be changed from many different places as part of many different use cases. Since an entity can not know what particular application use case it is being manipulated for, how can it know when it is the right time to call save? As a very simple example, if a use case were to change a Product's name and then immediately its product number, I wouldn't want to call save() on both the name change and the product number change - but just once when all the changes for that particular use case had been made ....
 
Anyway, just my 2c
 
Al
 
> Thanks for your replies, i'm still not sure why entities should be
> unaware of the need to save/commit themself after some change.
> From the rational point, it seems logical to me for an entity to call
> "save()" on some provider when some change is finished (for example
> when product entity finish to change its name, it calls IDao.save.
__._,_.___

Your email settings: Individual Email|Traditional
Change settings via the Web (Yahoo! ID required)
Change settings via email: Switch delivery to Daily Digest | Switch to Fully Featured
Visit Your Group | Yahoo! Groups Terms of Use | Unsubscribe

__,_._,___
Alasdair Gilmour | 2 Apr 14:36
Picon

Re: Should entities save/update themselves?

 Do you mean if the data for your entities is being changed externally by other applications/users at the same time as your application is running? Hibernate provides an optimistic concurrency control mechanism which can notify you that data has been changed "under your feet". This is detected before the transaction commits: an exception is thrown and the transaction rolls back. You can then retry the transaction, reloading the latest data. There are also API calls to "refresh" entities in the session with the latest state from the database, and to acquire locks on objects (which actually acquires locks on the underlying database rows) to prevent them being changed while you are manipulating them. All of these things potentially make the persist ence mechanism more intrusive, of course, but not overly so.
 
> Would this work if we made manual updates to the database either with SQL or through stored procedures?
> In practice we can not totally avoid them for a variety of reasons. We sometimes need information from objects
> updated this way within a session. Can you come up with designs that totally avoid these or do you have some
> tricks you 'd like to share?
__._,_.___

Your email settings: Individual Email|Traditional
Change settings via the Web (Yahoo! ID required)
Change settings via email: Switch delivery to Daily Digest | Switch to Fully Featured
Visit Your Group | Yahoo! Groups Terms of Use | Unsubscribe

__,_._,___
johnygold | 2 Apr 16:50
Picon
Favicon

Re: Should entities save/update themselves?

David,
When your DB change - nothing changes in the Domain. It's the IDao 
implementaion (located in different package/project) which changes. 

Al,
1. About seperation of concern:
Theoretically entities deal only with the Domain logic ("isolate the 
domain"), but practically sometime there is no escape from technical 
tasks. A real life example i had: Product entity which has "validate" 
method - it performs some business logic , then checks that all it's 
resources (images, custom files) are indeed on the physical disc, 
then continue with the business logic. The trade-off is between

(a) pure seperation of concern, preventing the Product entity from 
checking the disc and loosing it's ability to validate itself and 
perform atomic operation. It can indeed throw an event when the disc 
should be checked but then part of the validation will be external. 
After throwing an event, the entity will not know if the disc 
validation succeeded.

(b) atomic operation with minimal mixing of concern, the product 
entity is being inject with IPhysicalResourcesProvider which is being 
used to check the disc. This way all the validation phase is 
hapenning on the Product entity. And all it depends on is provider 
Interfaces. 

2. About saving/updating in many places:
You are right, the DB operation should be managed by some component 
who has birds-eye view on the transaction, but i think this should be 
the aggregate (Producy , in my case) and not the service. If the 
transaction is being shared by few aggregates, why won't you pass 
ITransaction to each aggregate?

Yoni

--- In domaindrivendesign <at> yahoogroups.com, "Alasdair Gilmour" 
<alasdairg@...> wrote:
>
> IMHO, its just down to separation of concerns and the Single 
Responsibility
> Principle: A Product entity represents a specific business concept 
in the
> domain. Saving an object's state to the database is a completely 
orthogonal
> responsibility that is nothing to do with "being a Product", so it 
doesn't
> conceptually belong within the Product entity.
> 
> Moreover, within an application, an entity can be changed from many
> different places as part of many different use cases. Since an 
entity can
> not know what particular application use case it is being 
manipulated for,
> how can it know when it is the right time to call save? As a very 
simple
> example, if a use case were to change a Product's name and then 
immediately
> its product number, I wouldn't want to call save() on both the name 
change
> and the product number change - but just once when all the changes 
for that
> particular use case had been made ....
> 
> Anyway, just my 2c
> 
> Al
> 
> > Thanks for your replies, i'm still not sure why entities should be
> > unaware of the need to save/commit themself after some change.
> > From the rational point, it seems logical to me for an entity to 
call
> > "save()" on some provider when some change is finished (for 
example
> > when product entity finish to change its name, it calls IDao.save.
>

------------------------------------


Gmane