Conditions

Conditional mapping of fields by predicates.

Conditions are used to determine wether a field should be mapped according to certain logic. In some use cases it is required to map a field from the source class only if some predicate is true, condition is that predicate.

We start with our two classes, our source class SimpleEntity and our destination class SimpleEntityDisplay.

data class SimpleEntity(
    val name: String
)
data class SimpleEntityDisplay(
    val name: String = ""
)

Creating Conditions

To create a condition, create a new class implementing the MappingCondition<T> interface.

class NotBlankStringCondition : MappingCondition<String> {
    override fun isValid(context: MappingConditionContext<String>): Boolean {
        return !context.originalValue.isNullOrBlank()
    }
}

The condition above checks that a string is not null or blank. After creating the condition class, all that is left is to use the condition.

Adding Conditions

Adding conditions to fields is available in both DSL and annotation mapping. Conditions can be added only to fields with the same type as the condition.

Annotations

The condition can be added to annotation mapping using the condition attribute.

@DefaultMappingTarget(SimpleEntityDisplay::class)
data class SimpleEntity(
    @MappedField(condition = NotBlankStringCondition::class)
    val name: String,
)

We mapped the name field and added the condition. Now the name field will be mapped to SimpleEntityDisplay only if its value is not null or blank.

Kotlin DSL

The condition can be added to field mapping using the withCondition function.

val mapper = mapper<SimpleEntity, SimpleEntityDisplay> {
    SimpleEntity::name mappedTo SimpleEntityDisplay::name withCondition NotBlankStringCondition::class
}

Using the DSL, conditions can also be added inline.

val mapper = mapper<SimpleEntity, SimpleEntityDisplay> {
    SimpleEntity::name mappedTo SimpleEntityDisplay::name withCondition {
        !it.originalValue.isNullOrBlank()
    }
}

Again, the name field will be mapped to SimpleEntityDisplay only if its value is not null or blank.

Java Builder

The condition can be added to field mapping builder using the withCondition function.

MappingDefinition mappingDefinition = new MappingDefinitionBuilder(SimpleEntity.class, SimpleEntityDisplay.class)
        .mapField("name", "name")
        .withCondition(NotBlankStringCondition.class)
        .build();

Also with the builder, conditions can also be added inline.

MappingDefinition mappingDefinition = new MappingDefinitionBuilder(SimpleEntity.class, SimpleEntityDisplay.class)
        .mapField("name", "name")
        .withCondition(context -> context.getOriginalValue() != null && !((String) context.getOriginalValue()).trim().isEmpty())
        .build();

Last updated