0

The application that I am working on has numerous ...toMany relations, e.i. class Model can have several parameters. In Unidirectional world, it is simple to manage a collection. I can clean the collection (Java List/set) and add elements again, very inefficient but for DB performance, but doable.

In a bidirectional word, mapping from DTO to an entity is a bit harder. I have to identify which elements in the collection changed, which were added and which were removed in the collection. That creates a lot of boilerplate code. Comparing IDs and filed values. If class Parameter has another ...toMany relation, this becomes a real mess and forces to create many loops.

A few possible solutions, hoping to get more form you!

  • Use model mappers such as (Dozer, MapStruct, ModelMapper, JMapper, ... you name it.) However trying ModelMapper I realized that this takes much more time than querying parameter from DB and editing only specific fields. Much more time for very complex objects.
  • Track collections, write a class that keeps track of changes. However, that would require editing code in many places as well as increase collection size (any known libraries/extensions to do thatß)
  • ???

What's the best approach to map DTO to entity and vice versa for a complex objects?

1

What's the best approach to map DTO to entity and vice versa for a complex objects?

The best approach is to not have complex objects. Many small objects are preferable to large god objects that try to do everything.

That said, how you solve the mapping problem depends on the kind of domain you're creating. An anemic domain is a slave to the DB. Whatever the DB says goes and you just deal with it. A rich domain actually has something to say about what concepts should and shouldn't exist and demands adapters, not simply a mapping, between itself and the DB, the GUI, reports, the internet, or whatever else.

I mention this to make you aware of the limitations of the mapping approach. It's used effectively in cases where the application is one of many that deal with the DB. But all you ever achieve is being yet another reporter to and of the DB. This severely limits how you can model the problem.

If you're fine with that the best test of having an effective mapping scheme is the ability to add a new field. The more things that need to be updated to add one field, the worse your mapping solution is.

1
  • As this is an excellent point and good practice for the future, it won't solve my current problem – Serafins Mar 21 '20 at 11:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.