1 package org.hibernate.ce.auction.persistence; 2 3 import org.hibernate.*; 4 import org.hibernate.usertype.CompositeUserType; 5 import org.hibernate.engine.SessionImplementor; 6 import org.hibernate.type.Type; 7 import org.hibernate.ce.auction.model.MonetaryAmount; 8 9 import java.io.Serializable ; 10 import java.math.BigDecimal ; 11 import java.sql.*; 12 import java.util.Currency ; 13 14 26 public class MonetaryAmountCompositeUserType 27 implements CompositeUserType { 28 29 public Class returnedClass() { return MonetaryAmount.class; } 30 31 public boolean equals(Object x, Object y) { 32 if (x == y) return true; 33 if (x == null || y == null) return false; 34 return x.equals(y); 35 } 36 public int hashCode(Object o) throws HibernateException { return o.hashCode(); } 37 public Serializable disassemble(Object o, SessionImplementor s) throws HibernateException { return (Serializable )o; } 38 public Object assemble(Serializable cached, SessionImplementor s, Object owner) throws HibernateException { return cached; } 39 public Object replace(Object o, Object o1, SessionImplementor s, Object o2) throws HibernateException { return null; } 41 42 public Object deepCopy(Object value) { 43 return value; } 45 46 public boolean isMutable() { return false; } 47 48 public Object nullSafeGet(ResultSet resultSet, 49 String [] names, 50 SessionImplementor session, 51 Object owner) 52 throws HibernateException, SQLException { 53 54 if (resultSet.wasNull()) return null; 55 BigDecimal value = resultSet.getBigDecimal( names[0] ); 56 Currency currency = 57 Currency.getInstance(resultSet.getString( names[1] ) ); 58 return new MonetaryAmount(value, currency); 59 } 60 61 public void nullSafeSet(PreparedStatement statement, 62 Object value, 63 int index, 64 SessionImplementor session) 65 throws HibernateException, SQLException { 66 67 if (value==null) { 68 statement.setNull(index, Types.NUMERIC); 69 statement.setNull(index+1, Types.VARCHAR); 70 } else { 71 MonetaryAmount amount = (MonetaryAmount) value; 72 String currencyCode = 73 amount.getCurrency().getCurrencyCode(); 74 statement.setBigDecimal( index, amount.getValue() ); 75 statement.setString( index+1, currencyCode ); 76 } 77 } 78 79 public String [] getPropertyNames() { 80 return new String [] { "value", "currency" }; 81 } 82 83 public Type[] getPropertyTypes() { 84 return new Type[] { Hibernate.BIG_DECIMAL, Hibernate.CURRENCY }; 85 } 86 87 public Object getPropertyValue(Object component, 88 int property) 89 throws HibernateException { 90 MonetaryAmount monetaryAmount = (MonetaryAmount) component; 91 if (property == 0) 92 return monetaryAmount.getValue(); 93 else 94 return monetaryAmount.getCurrency(); 95 } 96 97 public void setPropertyValue(Object component, 98 int property, 99 Object value) throws HibernateException { 100 throw new UnsupportedOperationException ("MonetaryAmount is immutable"); 101 } 102 103 } | Popular Tags |