1 package org.hibernate.type; 3 4 import java.io.Serializable ; 5 import java.util.HashMap ; 6 import java.util.Iterator ; 7 import java.util.Map ; 8 9 import org.dom4j.Element; 10 import org.hibernate.EntityMode; 11 import org.hibernate.HibernateException; 12 import org.hibernate.collection.PersistentCollection; 13 import org.hibernate.collection.PersistentMap; 14 import org.hibernate.collection.PersistentMapElementHolder; 15 import org.hibernate.engine.SessionImplementor; 16 import org.hibernate.persister.collection.CollectionPersister; 17 18 19 public class MapType extends CollectionType { 20 21 public MapType(String role, String propertyRef, boolean isEmbeddedInXML) { 22 super(role, propertyRef, isEmbeddedInXML); 23 } 24 25 public PersistentCollection instantiate(SessionImplementor session, CollectionPersister persister, Serializable key) { 26 if ( session.getEntityMode()==EntityMode.DOM4J ) { 27 return new PersistentMapElementHolder(session, persister, key); 28 } 29 else { 30 return new PersistentMap(session); 31 } 32 } 33 34 public Class getReturnedClass() { 35 return Map .class; 36 } 37 38 public Iterator getElementsIterator(Object collection) { 39 return ( (java.util.Map ) collection ).values().iterator(); 40 } 41 42 public PersistentCollection wrap(SessionImplementor session, Object collection) { 43 if ( session.getEntityMode()==EntityMode.DOM4J ) { 44 return new PersistentMapElementHolder( session, (Element) collection ); 45 } 46 else { 47 return new PersistentMap( session, (java.util.Map ) collection ); 48 } 49 } 50 51 public Object instantiate(Object original) { 52 return new HashMap (); 53 } 54 55 public Object replaceElements( 56 final Object original, 57 final Object target, 58 final Object owner, 59 final java.util.Map copyCache, 60 final SessionImplementor session) 61 throws HibernateException { 62 63 CollectionPersister cp = session.getFactory().getCollectionPersister( getRole() ); 64 65 java.util.Map result = (java.util.Map ) target; 66 result.clear(); 67 68 Iterator iter = ( (java.util.Map ) original ).entrySet().iterator(); 69 while ( iter.hasNext() ) { 70 java.util.Map.Entry me = (java.util.Map.Entry) iter.next(); 71 Object key = cp.getIndexType().replace( me.getKey(), null, session, owner, copyCache ); 72 Object value = cp.getElementType().replace( me.getValue(), null, session, owner, copyCache ); 73 result.put(key, value); 74 } 75 76 return result; 77 78 } 79 80 public Object indexOf(Object collection, Object element) { 81 Iterator iter = ( (Map ) collection ).entrySet().iterator(); 82 while ( iter.hasNext() ) { 83 Map.Entry me = (Map.Entry ) iter.next(); 84 if ( me.getValue()==element ) return me.getKey(); 86 } 87 return null; 88 } 89 90 } 91 | Popular Tags |