Using data mapper inside another data mapper in Ja

2019-08-20 02:54发布

问题:

I'm using the data mapper pattern in Java for accessing the database. Is it OK to call a mapper inside of another mapper? As far as I'm concerned, mappers should work on their own without a dependency on other mappers, but it seems that someone else who works on the same project with me has a different opinion.

To give an example: I have a Customer object and a ContactPerson object. The Customer has a ContactPerson object in it as a field. For getting data from a database, I have both a CustomerMapper and a ContactPersonMapper. When retrieving the Customer data from the database, I need to get its ContactPerson data at the same time. Is it a good idea to use the ContactPerson mapper inside my CustomerMapper, or should I make the mappers completely independent of each other?

回答1:

I guess you are using something similar to spring jdbctemplate and mappers here. I use that pattern a lot, and I tend to agree with you. I never call a second mapper inside a mapper. In my opinion the code is much easier to both test and read when the mappers are standalone. I prefer to have as little logic as possible in the DAOs, and leave logic to other code levels.

A few times in the past I made logic inside mappers to map structures to more advanced objects, but I have moved away from even doing that. I think the best apporach is to make the mappers very, very simple.