1 package org.hibernate.type; 3 4 import java.io.Serializable ; 5 import java.sql.PreparedStatement ; 6 import java.sql.ResultSet ; 7 import java.sql.SQLException ; 8 9 import org.hibernate.EntityMode; 10 import org.hibernate.Hibernate; 11 import org.hibernate.HibernateException; 12 import org.hibernate.engine.SessionImplementor; 13 import org.hibernate.util.SerializationHelper; 14 15 20 public class SerializableType extends MutableType { 21 22 private final Class serializableClass; 23 24 public SerializableType(Class serializableClass) { 25 this.serializableClass = serializableClass; 26 } 27 28 public void set(PreparedStatement st, Object value, int index) throws HibernateException, SQLException { 29 Hibernate.BINARY.set(st, toBytes(value), index); 30 } 31 32 public Object get(ResultSet rs, String name) throws HibernateException, SQLException { 33 34 byte[] bytes = (byte[]) Hibernate.BINARY.get(rs, name); 35 if ( bytes==null ) { 36 return null; 37 } 38 else { 39 return fromBytes(bytes); 40 } 41 } 42 43 public Class getReturnedClass() { 44 return serializableClass; 45 } 46 47 public boolean isEqual(Object x, Object y) throws HibernateException { 48 if (x==y) return true; 49 if (x==null || y==null) return false; 50 return Hibernate.BINARY.isEqual( toBytes(x), toBytes(y) ); 51 } 52 53 public int getHashCode(Object x, EntityMode entityMode) { 54 return Hibernate.BINARY.getHashCode( toBytes(x), entityMode ); 55 } 56 57 public String toString(Object value) throws HibernateException { 58 return Hibernate.BINARY.toString( toBytes(value) ); 59 } 60 61 public Object fromStringValue(String xml) throws HibernateException { 62 return fromBytes( (byte[]) Hibernate.BINARY.fromStringValue(xml) ); 63 } 64 65 public String getName() { 66 return (serializableClass==Serializable .class) ? "serializable" : serializableClass.getName(); 67 } 68 69 public Object deepCopyNotNull(Object value) throws HibernateException { 70 return fromBytes( toBytes(value) ); 71 } 72 73 private static byte[] toBytes(Object object) throws SerializationException { 74 return SerializationHelper.serialize( (Serializable ) object ); 75 } 76 77 private static Object fromBytes( byte[] bytes ) throws SerializationException { 78 return SerializationHelper.deserialize(bytes); 79 } 80 81 public int sqlType() { 82 return Hibernate.BINARY.sqlType(); 83 } 84 85 public Object assemble(Serializable cached, SessionImplementor session, Object owner) 86 throws HibernateException { 87 return (cached==null) ? null : fromBytes( (byte[]) cached ); 88 } 89 90 public Serializable disassemble(Object value, SessionImplementor session, Object owner) 91 throws HibernateException { 92 return (value==null) ? null : toBytes(value); 93 } 94 95 } 96 97 98 99 100 101 102 103 | Popular Tags |