1 package org.hibernate.test.sql; 2 3 import java.io.Serializable ; 4 import java.math.BigDecimal ; 5 import java.sql.PreparedStatement ; 6 import java.sql.ResultSet ; 7 import java.sql.SQLException ; 8 import java.sql.Types ; 9 import java.util.Currency ; 10 11 import org.hibernate.HibernateException; 12 import org.hibernate.usertype.UserType; 13 14 20 public class MonetaryAmountUserType 21 implements UserType { 22 23 private static final int[] SQL_TYPES = {Types.NUMERIC, Types.VARCHAR }; 24 25 public int[] sqlTypes() { return SQL_TYPES; } 26 27 public Class returnedClass() { return MonetaryAmount.class; } 28 29 public boolean isMutable() { return false; } 30 31 public Object deepCopy(Object value) { 32 return value; } 34 35 public boolean equals(Object x, Object y) { 36 if (x == y) return true; 37 if (x == null || y == null) return false; 38 return x.equals(y); 39 } 40 41 public Object nullSafeGet(ResultSet resultSet, 42 String [] names, 43 Object owner) 44 throws HibernateException, SQLException { 45 46 BigDecimal value = resultSet.getBigDecimal(names[0]); 47 if (resultSet.wasNull()) return null; 48 String cur = resultSet.getString(names[1]); 49 Currency userCurrency = Currency.getInstance(cur); 50 51 return new MonetaryAmount(value, userCurrency); 52 } 53 54 public void nullSafeSet(PreparedStatement statement, 55 Object value, 56 int index) 57 throws HibernateException, SQLException { 58 59 if (value == null) { 60 statement.setNull(index, Types.NUMERIC); 61 statement.setNull(index+1, Types.VARCHAR); 62 } else { 63 MonetaryAmount currency = (MonetaryAmount)value; 64 statement.setBigDecimal(index, currency.getValue()); 65 statement.setString(index+1, currency.getCurrency().getCurrencyCode()); 66 } 67 } 68 69 public Serializable disassemble(Object value) throws HibernateException { 70 return (Serializable ) value; 71 } 72 73 public Object assemble(Serializable cached, Object owner) throws HibernateException { 74 return cached; 75 } 76 77 public Object replace(Object original, Object target, Object owner) 78 throws HibernateException { 79 return original; 80 } 81 82 public int hashCode(Object x) throws HibernateException { 83 return x.hashCode(); 84 } 85 } 86 | Popular Tags |