创建CompositeUserType
public class MonetaryAmountCompositeUserType implements CompositeUserType{
@SuppressWarnings("unchecked")
public Class returnedClass() {
return MonetaryAmount.class;
}
public boolean isMutable() {
return false;
}
//创建值的快照
public Object deepCopy(Object value) throws HibernateException {
return value;
}
//以序列化的形式保存信息的高速缓存
public Serializable disassemble(Object value, SessionImplementor session)
throws HibernateException {
return (Serializable)value;
}
//高速缓存的数据转变为MonetaryAmount的一个实例
public Object assemble(Serializable cached, SessionImplementor session,
Object owner) throws HibernateException {
return cached;
}
//处理脱管对象状态的合并
public Object replace(Object original, Object target,
SessionImplementor session, Object owner) throws HibernateException {
return original;
}
public boolean equals(Object x, Object y) throws HibernateException {
if (x == y)
return true;
if (null == x || null == y)
return false;
return x.equals(y);
}
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
//从JDBC的ResultSet获取属性值
public Object nullSafeGet(ResultSet rs, String[] names,
SessionImplementor session, Object owner)
throws HibernateException, SQLException {
BigDecimal value = rs.getBigDecimal(names[0]);
if(rs.wasNull()) return null;
Currency currency = Currency.getInstance(rs.getString(names[1]));
return new MonetaryAmount(value,currency);
}
//把属性值写到JDBC的PreparedStatement
public void nullSafeSet(PreparedStatement st, Object value, int index,
SessionImplementor session) throws HibernateException, SQLException {
if(null == value){
st.setNull(index, BigDecimalType.INSTANCE.sqlType());
st.setNull(index+1, CurrencyType.INSTANCE.sqlType());
}else{
MonetaryAmount amount = (MonetaryAmount)value;
String currencyCode = amount.getCurrency()。getCurrencyCode();
st.setBigDecimal(index,amount.getAmount());
st.setString(index+1, currencyCode);
}
}
//公开值类型属性
public String[] getPropertyNames() {
return new String[] { "amount", "currency" };
}
//属性类型
public Type[] getPropertyTypes() {
return new Type[]{BigDecimalType.INSTANCE,CurrencyType.INSTANCE};
}
//返回MonetaryAmount的单个属性的值
public Object getPropertyValue(Object component, int property)
throws HibernateException {
MonetaryAmount monetaryAmount = (MonetaryAmount)component;
if(property == 0){
return monetaryAmount.getAmount();
}else{
return monetaryAmount.getCurrency();
}
}
public void setPropertyValue(Object component, int property, Object value)
throws HibernateException {
throw new UnsupportedOperationException("Immutable MonetaryAmount!");
}
}