KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hibernate > ce > auction > persistence > MonetaryAmountType


1 package org.hibernate.ce.auction.persistence;
2
3 import org.hibernate.usertype.*;
4 import org.hibernate.ce.auction.model.MonetaryAmount;
5 import org.hibernate.*;
6 import org.hibernate.engine.SessionImplementor;
7
8 import java.util.*;
9 import java.sql.*;
10 import java.math.BigDecimal JavaDoc;
11
12 /**
13  * This type adds parameterizable currency conversion to the normal composite user type,
14  * that is, you can set the target currency for the conversion (for the value saved and
15  * loaded from the database) to any ISO code in your mapping, depending on the
16  * situation/property to map. It maps a two-attribute component to two database columns.
17  *
18  * @see MonetaryAmountSimpleUserType
19  * @author Christian Bauer <christian@hibernate.org>
20  */
public class MonetaryAmountType extends MonetaryAmountCompositeUserType implements ParameterizedType {
21
22     // The amount
23
private Currency convertTo;
24
25     public void setParameterValues(Properties parameters) {
26         this.convertTo = Currency.getInstance(parameters.getProperty("convertTo"));
27     }
28
29     public Object JavaDoc nullSafeGet(ResultSet resultSet,
30                               String JavaDoc[] names,
31                               SessionImplementor session,
32                               Object JavaDoc owner)
33             throws HibernateException, SQLException {
34
35         if (resultSet.wasNull()) return null;
36         BigDecimal JavaDoc value = resultSet.getBigDecimal( names[0] );
37         // When loading, take the currency from the database
38
Currency currency = Currency.getInstance(resultSet.getString( names[1] ) );
39         return new MonetaryAmount(value, currency);
40     }
41
42     public void nullSafeSet(PreparedStatement statement,
43                             Object JavaDoc value,
44                             int index,
45                             SessionImplementor session)
46             throws HibernateException, SQLException {
47
48         if (value==null) {
49             statement.setNull(index, Types.NUMERIC);
50         } else {
51             MonetaryAmount amount = (MonetaryAmount) value;
52             // When saving, convert to target currency
53
MonetaryAmount dbAmount = MonetaryAmount.convert(amount, convertTo);
54             statement.setBigDecimal( index, dbAmount.getValue() );
55             statement.setString( index+1, dbAmount.getCurrency().getCurrencyCode());
56         }
57     }
58     
59 }
Popular Tags