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.joda;
17  
18  import java.math.BigDecimal;
19  
20  import org.jadira.usertype.moneyandcurrency.joda.columnmapper.IntegerColumnCurrencyUnitMapper;
21  import org.jadira.usertype.moneyandcurrency.legacyjdk.columnmapper.BigDecimalBigDecimalColumnMapper;
22  import org.jadira.usertype.spi.shared.AbstractMultiColumnUserType;
23  import org.jadira.usertype.spi.shared.ColumnMapper;
24  import org.joda.money.CurrencyUnit;
25  import org.joda.money.Money;
26  
27  /**
28   * Persists the decimal amount and currency from a Money instance
29   */
30  public class PersistentMoneyAmountAndCurrencyAsInteger extends AbstractMultiColumnUserType<Money> {
31  
32  	private static final long serialVersionUID = 3735995469031558183L;
33  
34  	private static final ColumnMapper<?, ?>[] COLUMN_MAPPERS = new ColumnMapper<?, ?>[] { new IntegerColumnCurrencyUnitMapper(), new BigDecimalBigDecimalColumnMapper() };
35  
36      private static final String[] PROPERTY_NAMES = new String[]{ "currencyUnit", "amount" };
37  	
38  	@Override
39  	protected ColumnMapper<?, ?>[] getColumnMappers() {
40  		return COLUMN_MAPPERS;
41  	}
42  
43      @Override
44      protected Money fromConvertedColumns(Object[] convertedColumns) {
45  
46          CurrencyUnit currencyUnitPart = (CurrencyUnit) convertedColumns[0];
47          BigDecimal amountPart = (BigDecimal) convertedColumns[1];
48          Money money = Money.of(currencyUnitPart, amountPart);
49  
50          return money;
51      }
52  
53      @Override
54      protected Object[] toConvertedColumns(Money value) {
55  
56          return new Object[] { value.getCurrencyUnit(), value.getAmount() };
57      }
58      
59      @Override
60  	public String[] getPropertyNames() {
61  		return PROPERTY_NAMES;
62  	}
63  }