📄 sessionimpl.java
字号:
loadedPersister=persister; role = (persister==null) ? null : persister.getRole(); } /*public boolean isInitialized() { return initialized; }*/ public boolean isNew() { return initialized && snapshot==null; //TODO: is this a correct implementation? } public boolean wasDereferenced() { return loadedKey==null; } } static final class CollectionKey implements Serializable { private String role; private Serializable key; CollectionKey(String role, Serializable key) { this.role=role; this.key=key; } CollectionKey(CollectionPersister persister, Serializable key) { this.role=persister.getRole(); this.key=key; } public boolean equals(Object other) { CollectionKey that = (CollectionKey) other; return that.role.equals(role) && that.key.equals(key); } public int hashCode() { return key.hashCode(); } } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { log.trace("deserializing session"); ois.defaultReadObject(); entityEntries = IdentityMap.deserialize( ois.readObject() ); collectionEntries = IdentityMap.deserialize( ois.readObject() ); arrayHolders = IdentityMap.deserialize( ois.readObject() ); initTransientState(); // we need to reconnect all proxies and collections to this session // the association is transient because serialization is used for // different things. Iterator iter = collectionEntries.entrySet().iterator(); while ( iter.hasNext() ) { try { Map.Entry e = (Map.Entry) iter.next(); ( (PersistentCollection) e.getKey() ).setCurrentSession(this); CollectionEntry ce = (CollectionEntry) e.getValue(); if ( ce.getRole()!=null ) ce.setLoadedPersister( factory.getCollectionPersister( ce.getRole() ) ); } catch (HibernateException he) { throw new InvalidObjectException( he.getMessage() ); } } iter = proxiesByKey.values().iterator(); while ( iter.hasNext() ) { Object proxy = iter.next(); if ( proxy instanceof HibernateProxy ) { HibernateProxyHelper.getLazyInitializer( (HibernateProxy) proxy ).setSession(this); } else { iter.remove(); //the proxy was pruned during the serialization process } } iter = entityEntries.entrySet().iterator(); while ( iter.hasNext() ) { EntityEntry e = (EntityEntry) ( (Map.Entry) iter.next() ).getValue(); try { e.persister = factory.getPersister(e.className); } catch (MappingException me) { throw new InvalidObjectException( me.getMessage() ); } } } private void writeObject(ObjectOutputStream oos) throws IOException { if ( isConnected() ) throw new IllegalStateException("Cannot serialize a Session while connected"); if ( insertions.size()!=0 || deletions.size()!=0 ) throw new IllegalStateException("Cannot serialize a Session which has work waiting to be flushed"); log.trace("serializing session"); oos.defaultWriteObject(); oos.writeObject( IdentityMap.serialize(entityEntries) ); oos.writeObject( IdentityMap.serialize(collectionEntries) ); oos.writeObject( IdentityMap.serialize(arrayHolders) ); } SessionImpl(Connection connection, SessionFactoryImpl factory, boolean autoclose, long timestamp, Interceptor interceptor) { this.connection = connection; connect = connection==null; this.interceptor = interceptor; this.autoClose = autoclose; this.timestamp = timestamp; this.factory = factory; entitiesByKey = new HashMap(50); proxiesByKey = new HashMap(10); nonExists = new HashSet(10); entityEntries = IdentityMap.instantiateSequenced(50); collectionEntries = IdentityMap.instantiateSequenced(30); collectionsByKey = new HashMap(30); arrayHolders = IdentityMap.instantiate(10); initTransientState(); log.debug("opened session"); } public Batcher getBatcher() { return batcher; } public SessionFactoryImplementor getFactory() { return factory; } public long getTimestamp() { return timestamp; } public Connection close() throws HibernateException { log.trace("closing session"); try { return (connection==null) ? null : disconnect(); } finally { cleanup(); } } public void afterTransactionCompletion(boolean success) { log.trace("transaction completion"); isCurrentTransaction = false; // Downgrade locks Iterator iter = entityEntries.values().iterator(); while ( iter.hasNext() ) { ( (EntityEntry) iter.next() ).lockMode = LockMode.NONE; } // Release cache softlocks int size = executions.size(); boolean invalidateQueryCache = factory.isQueryCacheEnabled(); for ( int i=0; i<size; i++ ) { try { Executable exec = (Executable) executions.get(i); try { exec.afterTransactionCompletion(success); } finally { if (invalidateQueryCache) factory.getUpdateTimestampsCache().invalidate( exec.getPropertySpaces() ); } } catch (CacheException ce) { log.error("could not release a cache lock", ce); // continue loop } catch (Exception e) { throw new AssertionFailure("Exception releasing cache locks", e); } } executions.clear(); } private void initTransientState() { insertions = new ArrayList(20); deletions = new ArrayList(20); updates = new ArrayList(20); collectionCreations = new ArrayList(20); collectionRemovals = new ArrayList(20); collectionUpdates = new ArrayList(20); executions = new ArrayList(50); batchLoadableEntityKeys = new SequencedHashMap(30); loadingCollections = new HashMap(); nonlazyCollections = new ArrayList(20); batcher = factory.isJdbcBatchUpdateEnabled() ? (Batcher) new BatchingBatcher(this) : (Batcher) new NonBatchingBatcher(this); } private void cleanup() { closed = true; entitiesByKey.clear(); proxiesByKey.clear(); entityEntries.clear(); arrayHolders.clear(); collectionEntries.clear(); nullifiables.clear(); batchLoadableEntityKeys.clear(); collectionsByKey.clear(); nonExists.clear(); /*insertions.clear(); deletions.clear(); updates.clear(); collectionCreations.clear(); collectionRemovals.clear(); collectionUpdates.clear();*/ } public LockMode getCurrentLockMode(Object object) throws HibernateException { if (object==null) throw new NullPointerException("null object passed to getCurrentLockMode()"); if ( object instanceof HibernateProxy ) { object = HibernateProxyHelper.getLazyInitializer( (HibernateProxy) object ).getImplementation(this); if (object==null) return LockMode.NONE; } EntityEntry e = getEntry(object); if (e==null) throw new TransientObjectException("Given object not associated with the session"); if ( e.status!=LOADED ) throw new ObjectDeletedException( "The given object was deleted", e.id, object.getClass() ); return e.lockMode; } public LockMode getLockMode(Object object) { return getEntry(object).lockMode; } private void addEntity(Key key, Object object) { entitiesByKey.put(key, object); batchLoadableEntityKeys.remove(key); } public Object getEntity(Key key) { return entitiesByKey.get(key); } private Object removeEntity(Key key) { return entitiesByKey.remove(key); } public void setLockMode(Object entity, LockMode lockMode) { getEntry(entity).lockMode = lockMode; } private EntityEntry addEntry( Object object, Status status, Object[] loadedState, Serializable id, Object version, LockMode lockMode, boolean existsInDatabase, ClassPersister persister, boolean disableVersionIncrement ) { EntityEntry e = new EntityEntry(status, loadedState, id, version, lockMode, existsInDatabase, persister, disableVersionIncrement); entityEntries.put(object, e); return e; } private EntityEntry getEntry(Object object) { return (EntityEntry) entityEntries.get(object); } private EntityEntry removeEntry(Object object) { return (EntityEntry) entityEntries.remove(object); } private boolean isEntryFor(Object object) { return entityEntries.containsKey(object); } private CollectionEntry getCollectionEntry(PersistentCollection coll) { return (CollectionEntry) collectionEntries.get(coll); } public boolean isOpen() { return !closed; } /** * Save a transient object ... an id is generated, assigned to the given * object and returned. */ public Serializable save(Object obj) throws HibernateException { if (obj==null) throw new NullPointerException("attempted to save null"); Object object = unproxy(obj); //throws exception if uninitialized EntityEntry e = getEntry(object); if ( e!=null ) { if ( e.status==DELETED ) { flush(); } else { log.trace( "object already associated with session" ); return e.id; } } Serializable id = saveWithGeneratedIdentifier(object, Cascades.ACTION_SAVE_UPDATE, null); //id might be generated by SQL insert reassociateProxy(obj, id); //TODO: move into saveWithGeneratedIdentifier()? return id; } private Serializable saveWithGeneratedIdentifier(Object object, Cascades.CascadingAction action, Object anything) throws HibernateException { ClassPersister persister = getPersister(object); try { Serializable id = persister.getIdentifierGenerator() .generate(this, object); if (id==null) { throw new IdentifierGenerationException("null identifier generated"); } else if (id==IdentifierGeneratorFactory.SHORT_CIRCUIT_INDICATOR) { return getIdentifier(object); //yick! } else if (id==IdentifierGeneratorFactory.IDENTITY_COLUMN_INDICATOR) { return doSave(object, null, persister, true, action, anything); } else { return doSave(object, id, persister, false, action, anything); } } catch (SQLException sqle) { throw new JDBCException("Could not save object", sqle); } } /** * Save a transient object with a manually assigned ID. */ public void save(Object obj, Serializable id) throws HibernateException { if (obj==null) throw new NullPointerException("attempted to insert null"); if (id==null) throw new NullPointerException("null identifier passed to insert()"); Object object = unproxy(obj); //throws exception if uninitialized! EntityEntry e = getEntry(object); if ( e!=null ) { if ( e.status==DELETED ) { flush(); } else { if ( !id.equals(e.id) ) throw new PersistentObjectException( "object passed to save() was already persistent: " + MessageHelper.infoString(e.persister, id) ); log.trace( "object already associated with session" ); } } doSave(object, id, getPersister(object), false, Cascades.ACTION_SAVE_UPDATE, null); reassociateProxy(obj, id); } private Serializable doSave( final Object object, final Serializable id, final ClassPersister persister, final boolean useIdentityColumn, final Cascades.CascadingAction cascadeAction, final Object anything) throws HibernateException { if ( log.isTraceEnabled() ) log.trace( "saving " + MessageHelper.infoString(persister, id) ); final Key key; if (useIdentityColumn) { // if the id is generated by the database, we assign the key later key = null; } else { key = new Key(id, persister); Object old = getEntity(key); if (old!= null) { if ( getEntry(old).status==DELETED ) { flush(); } else { throw new NonUniqueObjectException( id, persister.getMappedClass() ); } } persister.setIdentifier(object, id); }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -