【hibernate】自定义JAP转换器

【hibernate】自定义JAP转换器

转载:https://www.cnblogs.com/yangchongxing/p/10398255.html

1、转换基本属性

package cn.ycx.study.hibernate.bean;

import java.math.BigDecimal;
import java.util.Currency;

public class Money {
    public static final String SPLIT_SYMBOL = " ";
    protected BigDecimal value;
    protected Currency currency;
    public Money(BigDecimal value, Currency currency) {
        this.value = value;
        this.currency = currency;
    }
    public BigDecimal getValue() {
        return value;
    }
    public void setValue(BigDecimal value) {
        this.value = value;
    }
    public Currency getCurrency() {
        return currency;
    }
    public void setCurrency(Currency currency) {
        this.currency = currency;
    }
    @Override
    public String toString() {
        return getValue().toString() + SPLIT_SYMBOL + getCurrency();
    }
    public static Money fromString(String s) {
        String[] split = s.split(SPLIT_SYMBOL);
        return new Money(new BigDecimal(split[0]), Currency.getInstance(split[1]));
    }
}

转换器实现

package cn.ycx.study.hibernate.converter;

import javax.persistence.AttributeConverter;

import cn.ycx.study.hibernate.bean.Money;

public class MoneyConverter implements AttributeConverter<Money, String> {

    @Override
    public String convertToDatabaseColumn(Money attribute) {
        return attribute.toString();
    }

    @Override
    public Money convertToEntityAttribute(String dbData) {
        return Money.fromString(dbData);
    }

}

实体对象

package cn.ycx.study.hibernate.entity;

import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import cn.ycx.study.hibernate.bean.Money;
import cn.ycx.study.hibernate.converter.MoneyConverter;
@Entity
@org.hibernate.annotations.DynamicInsert
@org.hibernate.annotations.DynamicUpdate
public class User {
    @Id
    @GeneratedValue(generator="id_generator")
    protected long id;
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    @Convert(converter = MoneyConverter.class,disableConversion=false)
    protected Money money;
    public Money getMoney() {
        return money;
    }
    public void setMoney(Money money) {
        this.money = money;
    }
}

测试

    @Test
    public void testInsert() {
        User u = new User();
        u.setMoney(new Money(new BigDecimal(10), Currency.getInstance(Locale.CHINA)));
        this.session.persist(u);
        assertTrue( true );
    }

猜你喜欢

转载自www.cnblogs.com/yangchongxing/p/10398255.html