将自定义类保存到数据库中,自定义序列化规则 [英] Persist custom class into database, custom serialization rules

查看:350
本文介绍了将自定义类保存到数据库中,自定义序列化规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个课程

pre $ public class Money {
private BigDecimal amount;
私人字符串货币;
}

我想创建一个自定义的序列化器或类似的方法来告诉hibernate以这种方式将 Money 类持久保存为字符串 23.00 EUR



基本上,序列化将是金额用2位小数进行舍入+空格+ 货币,反序列化将遵循相反的逻辑。



实现起来应该不难,但我找不到提示。
任何想法如何做到这一点?

解决方案

准备去:AttributeConverter

  import javax.persistence.AttributeConverter; 


@Converter(autoApply = true)
公共类MoneyAttributeConverter实现了AttributeConverter< Money,String> {

@Override
public String convertToDatabaseColumn(Money in){
return ... convert here;
}

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


$ / code>

希望helpul:)

编辑。关于边距的说明,序列化与持久性是相似的,但不一样。 Google in the net @Transient 注释与瞬态关键字之间的差异

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?

解决方案

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"

这篇关于将自定义类保存到数据库中,自定义序列化规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆