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?

  • The delegated property is not ”real” property of its 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 a test example:

If you know a good example where to use delegated properties in practice, please, do let me know.

For more examples, unit tests and integration tests with Hibernate functionality where delegation “extends” the arms of Hibernate’s Entity, see demo my repository.

Source link