Let’s say you have an Entity:
You need to create a DTO for some reason. You probably do it like this:
Constructor here serves as a mapper. It maps Entity properties to DTO properties.
Types of DTO properties are resolved from its Entity. That’s good, we do not want to duplicate those types in DTO.
But you can also write DTO with delegated properties:
This looks almost the same as the first DTO. So what’s the difference?
- delegated property is not ”real” property of it’s class
- instead its getter and setter is delegated to Entity class
- when Entity property is changed, that change is reflected in DTO delegated property, even when DTO was instantiated before the change
- when DTO delegated property is changed, the change is reflected in Entity
- when we do not want to modify delegated property, we set it to val instead of var.
Let’s see it in test example:
If you know a good example where to use delegated properties in practice, please, do let me know in the comment.
For more examples, unit tests and integration tests with Hibernate functionality where delegation “extends” the arms of Hibernate’s Entity, see my tests.
Top comments (0)