Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persist custom class into database, custom serialization rules

Tags:

hibernate

jpa

I have this class

public class Money {
   private BigDecimal amount;
   private String currency;
}

I would like, by creating a custom serializator or similar ways, to tell hibernate to persist the Money class as String in this way: 23.00 EUR

Basically the serialization will be amount rounded with 2 decimals + space + currency, and the deserialization will follow the inverse logic.

It shouldn't be difficult to implement, but I couldn't find hints. Any ideas how to do that?

like image 472
Manza Avatar asked Feb 05 '26 10:02

Manza


1 Answers

Ready to go: AttributeConverter

import javax.persistence.AttributeConverter;


@Converter(autoApply = true)
public class MoneyAttributeConverter implements AttributeConverter<Money, String> {
    
    @Override
    public String convertToDatabaseColumn(Money in) {
        return ... convert here;
    }

    @Override
    public Money  convertToEntityAttribute(String in) {
        return ... and here;
    }
}

Hope helpul :)

EDIT. Note on the margin, serialisation is 'similar' to persistence, but not the same. Google in the net "differences between @Transient annotation and transient keyword"

like image 128
Jacek Cz Avatar answered Feb 12 '26 11:02

Jacek Cz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!