I want to implement a collection-based repository based on mybatis as the underlying persistence store. From "Implementing Domain-driven Design" (see chapter 12), it is indicated that the repository interface should mimic a Set
:
For example:
interface FlightRepository{
boolean add(Flight f);
boolean remove(Flight f);
// finder methods
Flight findById(Integer id);
}
The mybatis implementation would be something along the following lines (assuming spring boot implementation):
@Mapper
interface FlightMapper{
int createOrUpdate(Flight flight);
Flight read(int id);
int delete(Flight flight);
}
@Component
@Transactional
class FlightRepositoryImpl implements FlightRepository {
@AutoWired FlightMapper mapper;
boolean add(Flight f){
int affectedRows = mapper.createOrUpdate(f);
if(affectedRows == 1) return true
else return false;
}
boolean remove(Flight f){
int affectedRows = mapper.delete(f);
if (affectedRows == 1) return true
else return false;
}
Flight findById(){
return mapper.read(id);
}
}
My question is how can I manage repository updates without having a saveChanges
method:
Flight f = flightRepository.findById(1);
f.setDepartureTime(...);
f.setArrivalTime(...);
// flightRepository.saveChanges(); ??
One implementation option would be to have the repository make a copy of the original Flight object before returning it to the client. When the time comes to persist changes, it would compare its internal copy with the flight object returned to the client. If the internal copy does not match the object returned to the client, then the persistence store would be updated with the client's version (using flightMapper.createOrUpdate()
).
However, how can I trigger this logic, without having the client call an explicit saveChanges()
method? This would mean I would have to be able to somehow hook into the Repository object's lifetime using spring boot (in other words, trigger the updates before the transaction is being committed.