Domain driven design and transactions in Spring environment - java

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 pattern is called Transaction script. It's not considered a good practice since it leads to the procedural code, so I wanted to move forward to the domain driven design.
After reading couple of articles on the web, listening to the Chris Richardson's talk on Parleys and reading DDD chapters of the POJOs in Action, I think I got the big picture.
Problem is, that I don't know, how to organize transactions in my application. Chis Richardson in his book states:
The presentation tier handles HTTP requests from the user’s browser by calling
the domain model either directly or indirectly via a façade, which as I
described in the previous chapter is either a POJO or an EJB.
Good so far, but Srini Penchikala on InfoQ article states:
Some developers prefer managing the transactions in the DAO classes which is a poor design. This results in too fine-grained transaction control which doesn't give the flexibility of managing the use cases where the transactions span multiple domain objects. Service classes should handle transactions; this way even if the transaction spans multiple domain objects, the service class can manage the transaction since in most of the use cases the Service class handles the control flow.
Ok, so if I understand this correctly, repository classes should not be transactional, service layer (which is now much thinner) is transactional (as it used to be in Transaction script pattern). But what if domain objects are called by presentation layer directly? Does it mean, that my domain object should have transactional behavior? And how to implement it in Spring or EJB environment?
This seems kind of weird to me, so I'd be happy if somebody would clarify that. Thank you.

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.

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".

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.

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.

Related

Extra actions in a setter of a hibernate entity

I'm working on a legacy project with hibernate. Occasionally I find code where the developers wrote extra code in the set methods of entity objects. I'm wondering if this is an accepted practice ? Shouldn't hibernate entity objects just be pojo classes with extra annotations and maybe a few #Transient helper methods ?
If you want to do extra actions isn't that the responsibility of the service/dao working with the entity ?
What is the best practice ? Does anyone know of a blog or recognized article explaining this ?
IMHO, both approaches are correct. They both have its pros and cons. This is related to the everlasting Anemic model vs DDD (Domain-driven design) war.
Regarding Hibernate, it is quite flexible. It lets you took either approach you want. Performance and correctness of the solution don't depend on the decision you take, but on the correctness of the queries, database indexes, fetching strategies for entities, chosen algorithms, I/O handling, concurrency implementation, transaction management, etc.
If you go by DDD, the entities would be part of the business layer, while Hibernate itself (Session, SessionFactory and the whole ORM) would be part of the persistence layer. In this case, the entities would contain annotations related to persistence, which would be just hints for the ORM.
You should also be careful with transaction management. This is better accomplished outside of the entities. (Actually, one main advantage of the anemic model is that transaction management is very easy, because you wrap every service method of your business layer inside a transactional unit).
As you've mentioned you have a mix of both "ideologies", maybe you could use that fact as an advantage: let service methods delegate the logic to domain entities, but keep transaction management in your business services.

What is the difference between procedural code and Domain Driven Design style code?

I am going through Domain Driven Design(DDD) techniques and I am feeling like I didn't understand it well yet.
DDD suggests putting the business logic(not infrastructure stuff like persistence, security etc) in Domain Objects, Repositories for Persistence, Aggregators for assembling Domain Objects for Client(Presentation), Services which are thin layer on top of the Domain objects and Repositories, Aggregators and acts as Transactional boundary.
Let me put it in this way:
In DDD, ViewController --> SomeService --> {Domain Objects, Repositories, Aggregators}
In my current (Procedural style) approach:
ViewController --> SomeService --> DAO/Repository
Here ViewController talks to one or more Services to pull/push the data from/to the database using DAOs. If any business logic which only operates on properties of a Domain object will be in a method in that Domain Object itself. And finally the data got from service(s) are aggregated into DTOs to be presented in View Layer.
So to me both approaches almost looks similar.
Can someone explain me what I am missing?
P.S: I am adding some more info to better explain my question.
In theory everyone is saying DDD suggests "Logic should be in Domain Objects". OK.
Let us take a real scenario.
In ShoppingCart application, some user placed an Order. To process the Order I need to do all the following sub-tasks:
Get Each Item details and calculate the total Order Price.
Get the Delivery Address and Validate it using some Address Verification Service
Validate/Authenticate CreditCard Details
Save all the Order related info into DB
So by following DDD I will put the logic,
Order Total calculation in Order object which loops through its List objects.
In Address Object i would have validate() method which invokes some BING address validation.
In CreditCard class I would have authorize() method which calls some CCAuthorizationService to authorize using some third party services.
Save all order stuff into DB using some Repositories.
All these steps will be triggered by calling Order.process()
If this is correct DDD approach? If it is, our Domain Objects directly interacting with Repositories which seems to be violation of separation of concerns.
If this is not correct DDD approach, can some one please tell me how do you design for the above usecase?
DDD is language independent, it's about understanding the domain through experts and building a common language with which you can talk about the domain. So it cannot be compared directly to functional, procedural or object oriented programming languages, as they're not comparable.
View Controllers are specific to MVC frameworks and aren't specific to DDD.
In MVC a DTO for preparing data for the view would be a View Model.
Hope some of this helps.
It boils down to where the logic lives. In DDD logic primarily goes into the model layer so it stays near the data. In procedural code, logic goes into transactional layers so it is separated from the data. Fowler has a good description you can read about here.
They are similar.
Hopefully you're actually comparing "OOP" with "DDD". DDD is a subset of OOP (IMO), or at least should be in an OOPL. DDD is a specific way of thinking about breaking up responsibilities.
It's not about the technology or OOP or anything like that.
It's about focusing on the domain at hand, the language used by domain experts, understanding the domain and modelling that domain so that important concepts are present in the code.
It was originally done using OOP and many claimed that it could only be done using OOP.
However, lately people like Greg Young have shown how to do DDD in functional languages and still keep the focus on the domain.
Procedural code tend to ignore all that and just focus on how to read/write data from whatever datasource there is. e.g. integrating with a system like Movex there will be a billion tables and columns with completely retarded names like TAXEM.YAROOD FOOB.AAR which makes no sense to anyone reading that code...

Simple but good pattern for EJB

What would you suggest as a good and practical but simple pattern for a solution with:
HTML + JSP (as a view/presentation)
Servlets (controller, request, session-handling)
EJB (persistence, businesslogic)
MySQL DB
And is it necessary to use an own layer of DAO for persistence? I use JPA to persist objects to my DB.
Should I withdraw business logic from my EJB? All online sources tell me different things and confuses me...
I would definitely put the business logic in Stateless Session Beans. Stateless session beans are nice as they nicely capture the transaction boundaries. And it decouples the View layer from the persistence layer.
Take care that the methods of the SSB correspond to small business goals the user wants to achieve.
Another point is that you must be sure that the data you return has all data in the object tree and that you do not rely on lazy loading to get the rest, because this causes all kind of problems.
Stay as far away as possible from Stateful Session Beans : they are bad news and are a broken concept in the context of a web application.
For long running things, consider using Message Driven Beans which you trigger by sending a JMS message. These are a nice way to do background processing which frees the business logic faster, keeps transactions shorter and returns control to the end user faster.
What would you suggest as a good and practical but simple pattern for a solution with JSP/Servlets + EJB + MySQL
Use the MVC framework of your choice, Stateless Session Beans for the business logic and transaction management (prefer local interfaces if you don't need remoting), Entities for persistence.
Inject your EJBs wherever possible (if you are using Java EE 6, this means anywhere and you can also skip the interface).
And is it necessary to use an own layer of DAO for persistence? I use JPA to persist objects to my DB.
Some might say yes, I say no in most cases. The EntityManager already implements the Domain Store pattern, there is no need to shield it behind a DAO for simple needs.
You might want to read the following resources for more opinions on this:
Has JPA Killed the DAO?,
JPA/EJB3 killed the DAO,
and the more recent DAOs Aren't Dead - But They Either Collapsed Or Disappeared
Should I withdraw business logic from my EJB?
I wouldn't. Put your business logic in your (Stateless) Session Beans. EJB3 are POJOs, they are easily testable, there is no need to delegate the business logic to another layer.
Anno 2012 I would not recommend going for Servlets and JSP as the presentation layer. This was all the rage in 2002, but that's a decade ago.
Today Java EE has an excellent MVC framework build in called JSF. You are much better off using this instead. You most likely want to fetch some Widgets from the component library PrimeFaces, as all the standard ones are a bit basic. A utility library like OmniFaces is a great addition as well.
Regarding the DAOs; don't go as far as directly using the entity manager in (JSF) backing beans, but if you are already using Service classes (transactional boundaries) for your business logic , using a DAO as well might be overkill.
There are still some small advantages of a DAO, like a dao.findByName(...) looks a little clearer than loading a named query, setting a parameter, and getting a (single) result, but the cost is that you have to maintain a seperate DAO for each Entity, probably in addition to some Service.

What pattern fits between a façade and a DAO?

I'm in the process of designing part of my companies architecture for its Java EE web applications. I'm pretty clear on the reasons to use a façade and one or more DAOs. The problem I have is this:
There will be some logic that definitely belongs in the integration tier because it's all about keeping the data model consistent. Except the logic goes beyond simply maintaining referential integrity and other 'raw' persistence tasks which will be handled by JPA and Hibernate. I don't class this as business logic because it's separate to any business function. However, my understanding is that a DAO should only implement the logic required to access and persist objects to the data source.
My conclusion is that I need a 'business object'-like pattern which is appropriate for the integration tier. I've looked around and the closest thing I have found (yet still not quite right to my mind) is the Sun Transfer Object Assembler pattern.
Either there's a gap in my understanding of Java EE or there is a pattern out there that will fit.
maybe a mediator is what you want:
Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
then you can use a DaoMediator in order to coordinate two or more DAOs
It sounds to me like you may be missing a controller, and consequently may need the MVC pattern. The controller will look after the DAOs and present a consistent view (don't think in terms of GUIs, burt rather some client-facing interface). When modifications are made via this view, then the controller coordinates the changes to the model via the DAO. I suspect that your facade objects may be the view in this scenario.
Having said this, I wouldn't worry too much about identifying particular patterns. You often find that taking into account all your requirements and separating concerns where applicable, that you end up implementing a particular pattern and only identify it as such after the fact.
Have you considered using aggregates from Domain Driven Design?
I'm a student of DDD myself and it seems the business logic you're trying to design could be accomplished by richer POJO-like domain models. You'd have each
domain object to be responsible for its aggregate objects, and also including any logic concerning that business concept; that said, your integration layer would coordinate those rich objects but would refrain from having real logic per se (i.e several conditional logic).
Perhaps the pattern you're trying to find is actually a step into richer domain objects?
I think it's a DataMapper (or Adapter) pattern between your DAL and your Business Layer, but without a more concrete understanding i couldn't be sure.
What is driving the requirement for consistency between the DAOs? If there is some business assumption that is dictating the relationship. For example, you might have an invoice type that when it is 'Capital' then we have to make sure several other objects are in the right state or have the right set of values. This is definitely outside the realm of the data-layer.
I wouldn't try to hard to find the perfect pattern for this case. You need some sort of coordinating class though, a mediator or controller of some sort.

Three tier layered application using Wicket + Spring + Hibernate. How would you handle transactions?

I'm thinking about using the Open Session In View (OSIV) filter or interceptor that comes with Spring, as it seems like a convenient way for me as a developer. If that's what you recommend, do you recommend using a filter or an interceptor and why?
I'm also wondering how it will mix with HibernateTemplate and if I will lose the ability to mark methods as #Transactional(readOnly = true) etc and thus lose the ability to get some more fine grained transaction control?
Is there some kind of best practice for how to integrate this kind of solution with a three tier architecture using Hibernate and Spring (as I suppose my decision to use Wicket for presentation shouldn't matter much)?
If I use OSIV I will at least never run into lazy loading exceptions, on the other hand my transaction will live longer before being able to commit by being uncommitted in the view as well.
It's really a matter of personal taste.
Personally, I like to have transaction boundaries at the service layer. If you start thinking SOA, every call to a service should be independent. If your view layer has to call 2 different services (we could argue that this is already a code smell) then those 2 services should behave independently of each other, could have different transaction configurations, etc... Having no transactions open outside of the services also helps make sure that no modification occurs outside of a service.
OTOH you will have to think a bit more about what you do in your services (lazy loading, grouping functionalities in the same service method if they need a common transactionality, etc ...).
One pattern that can help reduce lazy-loading error is to use Value Object outside of the service layer. The services should always load all the data needed and copy it to VOs. You lose the direct mapping between your persistent objects and your view layer (meaning you have to write more code), but you might find that you gain in clarity ...
Edit: The decision will be based on trade offs, so I still think it is at least partly a matter of personal taste. Transaction at the service layer feels cleaner to me (more SOA-like, the logic is clearly restrained to the service layer, different calls are clearly separated, ...). The problem with that approach is LazyLoadingExceptions, which can be resolved by using VO. If VO are just a copy of your persistent objects, then yes, it is clearly a break of the DRY principle. If you use VO like you would use a database View, then VO are a simplification of you persistent objects. It will still be more code to write, but it will make your design clearer. It becomes especially useful if you need to plug some authorization scheme : if certain fields are visible only to certain roles, you can put the authorization at the service level and never return data that should not be viewed.
If I use OSIV I will at least never
run into lazy loading exceptions
that is not true, in fact its extremely easy to run into the infamous LazyInitializationException, just load an object, and try to read an attribute of it, after the view, depending on your configuration you WILL get the LIE

Categories