Domain driven design and transactions in Spring environment

后端 未结 4 1209
-上瘾入骨i
-上瘾入骨i 2020-12-24 02:50

I used to design my application around anemic domain model, so I had many repository object, which were injected to the big, fat, transaction-aware service layer. This patte

相关标签:
4条回答
  • 2020-12-24 03:32

    I think one easy way to get started with DDD and Spring and have good examples of how to deal with transactions is by looking at one of the sample apps that get shipped with Spring Roo. Roo churns out code that follows the DDD principles. It relies heavily on AspectJ. I suspect it was implemented building on the ideas put forward (back in 2006) by one of SpringSource's heavyweights, Ramnivas Laddad, in this talk.

    0 讨论(0)
  • 2020-12-24 03:36

    Unnfortunately I haven't make myself familiar with Spring but I will give feedback about your DDD understanding. Reading your description of transaction it is obvious that you haven't understand DDD especially Aggregate, Aggregate Root, and Repository concept.

    In DDD transaction can't span across aggregates so one Aggregate will always have one transaction.

    0 讨论(0)
  • 2020-12-24 03:40

    See this extremely useful blog-post. It explains how to achieve smooth DDD while not loosing Spring's and JPA's capabilities. It is centered around the @Configurable annotation.

    My opinion on these matters is a bit non-popular. Anemic data model is actually not wrong. Instead of having one object with data+operations, you have two objects - one with data and one with operations. You can view them as one object - i.e. satisfying DDD, but for the sake of easier use they are physically separated. Logically they are the same.

    Yes, this breaks encapsulation, but it doesn't make you use some 'magic' (aop + java agent) in order to achieve your goals.

    As for the transactions - there is something called Transaction propagation. Spring supports it with @Transactional(propagation=Propagation.REQUIRED). See this, point 9.5.7. In case you want your transactions to span multiple methods (of multiple objects) you can change the propagation attribute accordingly.

    You can also use @Transactional in your service layer, where appropriate, but this might introduce a lot of boilerplace service-classes in cases when you want to use simple, single-step operations like "save".

    0 讨论(0)
  • 2020-12-24 03:47

    My personal take on applying DDD with Spring and Hibernate, so far, is to have a stateless transactional service layer and access the domain objects through that. So the way I'm doing it the domain model does not know about transactions at all, that is handled entirely by the services.

    There is an example application you might find helpful to take a look at. It looks like Eric Evans was involved in creating it.

    0 讨论(0)
提交回复
热议问题