问题描述
我正在使用Java中的数据映射器模式来访问数据库.在另一个映射器内部调用一个映射器可以吗?就我而言,映射器应该独立工作而不依赖于其他映射器,但是似乎其他与我一起从事同一项目的人有不同的看法.
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.
举个例子:我有一个Customer对象和一个ContactPerson对象.客户在其中具有一个ContactPerson对象作为字段.为了从数据库中获取数据,我同时拥有一个CustomerMapper和一个ContactPersonMapper.从数据库检索客户数据时,我需要同时获取其ContactPerson数据.在我的CustomerMapper中使用ContactPerson映射器是一个好主意,还是应该使映射器彼此完全独立?
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?
推荐答案
我猜您在这里使用的是类似于spring jdbctemplate和mapper的东西.我经常使用这种模式,我倾向于同意你的看法.我从不在映射器内调用第二个映射器.我认为,当映射器是独立的时,该代码更易于测试和阅读.我更希望DAO中的逻辑尽可能少,而将逻辑留给其他代码级别.
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.
这篇关于在Java中的另一个数据映射器中使用数据映射器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!