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
)
public class SimpleEntity {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
data class SimpleEntityDisplay(
val name: String = ""
)
public class SimpleEntityDisplay {
private String name = "";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
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()
}
}
public class NotBlankStringCondition implements MappingCondition<String> {
@Override
public boolean isValid(@NonNull MappingConditionContext<String> context) {
return context.getOriginalValue() != null && !context.getOriginalValue().trim().isEmpty();
}
}
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,
)
@DefaultMappingTarget(SimpleEntityDisplay.class)
public class SimpleEntity {
@MappedField(condition = NotBlankStringCondition.class)
private String name;
// Getters and Setters...
}
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.