View Javadoc
1   /*
2    *  Copyright 2010, 2011, 2012 Christopher Pheby
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   */
16  package org.jadira.usertype.moneyandcurrency.moneta;
17  
18  import java.math.BigDecimal;
19  
20  import javax.money.CurrencyUnit;
21  import javax.money.MonetaryAmount;
22  
23  import org.jadira.usertype.moneyandcurrency.legacyjdk.columnmapper.BigDecimalBigDecimalColumnMapper;
24  import org.jadira.usertype.moneyandcurrency.moneta.columnmapper.StringColumnCurrencyUnitMapper;
25  import org.jadira.usertype.spi.shared.AbstractMultiColumnUserType;
26  import org.jadira.usertype.spi.shared.ColumnMapper;
27  import org.javamoney.moneta.FastMoney;
28  
29  /**
30   * Persists the decimal amount and currency from a FastMoney instance
31   */
32  public class PersistentFastMoneyAmountAndCurrency extends AbstractMultiColumnUserType<MonetaryAmount> {
33  
34  	private static final long serialVersionUID = 3735995469031558183L;
35  
36  	private static final ColumnMapper<?, ?>[] COLUMN_MAPPERS = new ColumnMapper<?, ?>[] { new StringColumnCurrencyUnitMapper(), new BigDecimalBigDecimalColumnMapper() };
37  
38      private static final String[] PROPERTY_NAMES = new String[]{ "currencyUnit", "amount" };
39  	
40  	@Override
41  	protected ColumnMapper<?, ?>[] getColumnMappers() {
42  		return COLUMN_MAPPERS;
43  	}
44  
45      @Override
46      protected FastMoney fromConvertedColumns(Object[] convertedColumns) {
47  
48          CurrencyUnit currencyUnitPart = (CurrencyUnit) convertedColumns[0];
49          BigDecimal amountPart = (BigDecimal) convertedColumns[1];
50          FastMoney money = FastMoney.of(amountPart, currencyUnitPart);
51  
52          return money;
53      }
54  
55      @Override
56      protected Object[] toConvertedColumns(MonetaryAmount value) {
57  
58          return new Object[] { value.getCurrency(), value.getNumber().numberValue(BigDecimal.class) };
59      }
60      
61      @Override
62  	public String[] getPropertyNames() {
63  		return PROPERTY_NAMES;
64  	}
65  }