How to create domain model with java resultset using the data mapper pattern?
Well I was wondering how to create domain models given Java's ResultSet Object in data mappers. I read Martin Fowler's book, and in his examples he was loading each field from ResultSet into local variables in the data mapper's method that creates domain models and then pass all these local variables to the domain model's constructor one by one.
The problem is that it only works if the table contains like 2-5 columns, otherwise you end up with 10+ local variables and a constructor that accepts 10+ parameters. I dont like constructors or methods that accept more than 5 parameters, 10+ is way too many. Not mentioning that my domain models' constructors also have arguments from dependency injection, such as UnitOfWork. In a word, I dont want to mess up the constructor's signature.
I have two possible solutions, but both seem to have issues. I can definitely pass the entire ResultSet into domain model's constructor, this way the constructor will only have 2-3 parameters. There is also an issue involved with this, the domain model and the domain layer is now aware of the existence of ResultSet. As far as I know, the data mapper is supposed to serve as a mediator between domain models and resultsets. If the domain model is directly manipulating resultset, it is a bad architectural design. In a long run it will cause even more problems.
I can also create an empty domain model first and then use its setter methods to add values to its fields. The problem with this approach is that, well, I have a UnitOfWork monitoring the domain model's state as new, dirty, removed or clean. The mechanism of UnitOfWork is that whenever the domain model's setter methods are invoked, it marks the object as dirty and pending for DB update. Consequently, using the empty domain model + setter approach leads to the object being marked as dirty each time the setter is invoked. Even though I can mark the domain model as clean before returning it, the entire process is still slow when I am loading a collection of objects.
So what do you think? Is there an alternative way to create domain model given a Java ResultSet that is both elegant and not resource-consuming? I am out of ideas...
您可以考虑使用Builder模式从ResultSet
构建模型。
上一篇: 保持DAO和域对象分离