In an application, there are at least two ways for dealing with domain object persistence and an ORM.
- Mapping directly the domain object to persistence using some kind of ORM (xml or annotations)
- Making separation of concerns in case of a lot of impedance mismatch between your domain and your persistent model (table columns). That means, domain object is persistence agnostic and there are some conversions to some corresponding persistent object, this latter maps to an ORM.
As pure DDD developers know, domain should not be driven by your database needs, thus in my project, I use this separation of concerns. Someone would think of YAGNI, someone would say "great" (like here). My project will need some different databases according to my need of reusability, so I chose the separation of concerns between my domain model and my persistent model.
But I came across an issue (some kind of performance loss), with Spring-Data.
A detail maybe, but just assume an ORM that doesn't have the functionnality of merge
, or anything related, to reattach detached entities to the current transaction.
To understand, let's suppose this conceptual code (in Java):
@Transaction
public void participateToMeeting(String userId, String meetingId){
User user = userRepository.ofId(userId); //returns a User domain type
Meeting meeting = meetingRepository.ofId(meetingId); //returns a Meeting domain type
if(user != null && meeting != null) {
user.participate(meeting); // as attached entity, this would automatically persist the relationship
}
}
But if henceforth, persistence occurs on the persistent model, not the domain model directly, we'd lose the attachement, since during conversion from domain to persistent object (indeed, repositories would now deal with persistent objects (instead of domain model directly) and merely convert the result as domain object as return type), the managedEntity
state is lost.
@Transaction
public void participateToMeeting(String userId, String meetingId){
User user = userRepository.ofId(userId); //returns a User domain type (converted from UserPO to User)
Meeting meeting = meetingRepository.ofId(meetingId); //returns a Meeting domain type (converted from MeetingPO to UserPO)
if(user != null && meeting != null) {
userRepository.participateToMeeting(user, meeting);
//although not conventional, adding this kind of method allows to convert User and Meeting to some persistent object: UserPO and MeetingPO, before proceeding to persistence
}
}
Here's the issue:
While converting from User
to UserPO
(in my infrastructure layer), I lose the entity "attachment". Thus, in the userRepository.participateToMeeting
method, I have to retrieve UserPO
and MeetingPO
again from database (to make them attached)...therefore involving, two additional requests.
Is there a better practice to deal with conversions domain object/persistent object without this performance loss?