Interface AttributeConverter<X, Y>
- Type Parameters:
-
X- the target type, that is, the type of the entity attribute -
Y- a basic type or a supported type in the NoSQL database representing the type of the database column
This interface is implemented by custom attribute converters. A converter is a class whose methods convert between the target type of the converter (an arbitrary Java type which may be used as the type of a persistent field or property) and a basic type or a type that can be persisted by a persistence provider, used as an intermediate step in mapping to the database representation.
A converted field or property is considered basic, since, with the aid of the converter, its values can be represented as instances of a basic type.
Note that the target type X and the converted basic
type Y may be the same Java type.
Example: Using a record Money value object with a
custom converter
public record Money(Currency currency, BigDecimal amount) {
@Override
public String toString() {
return currency.getCurrencyCode() + " " + amount;
}
public static Money fromString(String value) {
String[] parts = value.split(" ");
return new Money(Currency.getInstance(parts[0]), new BigDecimal(parts[1]));
}
}
Converter implementation:
public class MoneyConverter implements AttributeConverter<Money, String> {
@Override
public String convertToDatabaseColumn(Money attribute) {
return attribute == null ? null : attribute.toString();
}
@Override
public Money convertToEntityAttribute(String dbData) {
return dbData == null ? null : Money.fromString(dbData);
}
}
Example usage in an entity:
@Entity
public class Product {
@Id
private String id;
@Column
private String name;
@Column
@Convert(MoneyConverter.class)
private Money price;
}
The representation stored in the database (depending on the NoSQL backend) may resemble:
{
"id": "P-001",
"name": "Laptop",
"price": "USD 1499.00"
}
- Since:
- 1.0.0
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionconvertToDatabaseColumn(X attribute) Converts the value stored in the entity attribute into the data representation to be stored in the database.convertToEntityAttribute(Y dbData) Converts the data stored in the database column into the value to be stored in the entity attribute.
-
Method Details
-
convertToDatabaseColumn
-
convertToEntityAttribute
Converts the data stored in the database column into the value to be stored in the entity attribute. Note that it is the responsibility of the converter writer to specify the correct database data type for the corresponding column for use by the NoSQL database: i.e., persistence providers are not expected to do such type conversion.- Parameters:
-
dbData- the data from the database column to be converted - Returns:
- the converted value to be stored in the entity attribute
-