db-ojb-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From mattba...@apache.org
Subject cvs commit: jakarta-ojb/src/java/org/apache/ojb/broker/accesslayer RsIterator.java
Date Fri, 20 Dec 2002 19:25:31 GMT
mattbaird    2002/12/20 11:25:31

  Modified:    src/java/org/apache/ojb/broker/accesslayer RsIterator.java
  Log:
  add size() support for forward only resultsets
  
  Revision  Changes    Path
  1.22      +199 -171  jakarta-ojb/src/java/org/apache/ojb/broker/accesslayer/RsIterator.java
  
  Index: RsIterator.java
  ===================================================================
  RCS file: /home/cvs/jakarta-ojb/src/java/org/apache/ojb/broker/accesslayer/RsIterator.java,v
  retrieving revision 1.21
  retrieving revision 1.22
  diff -u -r1.21 -r1.22
  --- RsIterator.java	1 Dec 2002 11:46:40 -0000	1.21
  +++ RsIterator.java	20 Dec 2002 19:25:30 -0000	1.22
  @@ -54,14 +54,6 @@
    * <http://www.apache.org/>.
    */
   
  -import java.sql.SQLException;
  -import java.util.Collection;
  -import java.util.HashMap;
  -import java.util.List;
  -import java.util.Map;
  -import java.util.NoSuchElementException;
  -import java.util.Vector;
  -
   import org.apache.ojb.broker.Identity;
   import org.apache.ojb.broker.PersistenceBrokerException;
   import org.apache.ojb.broker.VirtualProxy;
  @@ -77,6 +69,10 @@
   import org.apache.ojb.broker.util.logging.Logger;
   import org.apache.ojb.broker.util.logging.LoggerFactory;
   
  +import java.sql.SQLException;
  +import java.sql.ResultSet;
  +import java.util.*;
  +
   /**
    * RsIterator can be used to iterate over a jdbc ResultSet to retrieve
    * persistent objects step-by-step and not all at once.
  @@ -135,13 +131,13 @@
   	 * flag that indicates wether hasNext on m_rs has allready been called
   	 */
   	protected boolean hasCalledCheck = false;
  -    
  -    /**
  -     * prefetch relationship:
  -     * inBatchedMode true prevents releasing of DbResources
  -     * IN_LIMIT defines the max number of values of sql (IN) , -1 for no limits
  -     */ 
  -    protected boolean inBatchedMode = false;
  +
  +	/**
  +	 * prefetch relationship:
  +	 * inBatchedMode true prevents releasing of DbResources
  +	 * IN_LIMIT defines the max number of values of sql (IN) , -1 for no limits
  +	 */
  +	protected boolean inBatchedMode = false;
   
   	/**
   	 * return value of the previously called hasNext from m_rs
  @@ -151,7 +147,7 @@
   	private boolean advancedJDBCSupport = false;
   	private boolean JDBCSupportAssessed = false;
   	private Query m_query = null;
  -        private int m_current_row = 0;
  +	private int m_current_row = 0;
   
   	protected Class getExtentClass()
   	{
  @@ -204,10 +200,10 @@
   			if (hasNext)
   			{
   				Object obj = getObjectFromResultSet();
  -                                m_current_row++;
  +				m_current_row++;
   
   				// Invoke events on PersistenceBrokerAware instances and listeners
  -                                m_broker.invokeEvent(obj,PersistenceBrokerImpl.EVENT_AFTER_LOOKUP);
  +				m_broker.invokeEvent(obj, PersistenceBrokerImpl.EVENT_AFTER_LOOKUP);
   
   				return obj;
   			}
  @@ -244,7 +240,7 @@
   	public RsIterator(Query query, ClassDescriptor mif, PersistenceBrokerImpl broker)
   	{
   		this();
  -		if (logger.isDebugEnabled())  logger.debug("RsIterator(" + query + ", " + mif + ")");
  +		if (logger.isDebugEnabled()) logger.debug("RsIterator(" + query + ", " + mif + ")");
   
   		m_rsAndStmt = new JdbcAccess(broker).executeQuery(query, mif);
   		m_row = new HashMap();
  @@ -253,13 +249,13 @@
   		m_cld = mif;
   		itemProxyClass = mif.getProxyClass();
   
  -  	    prefetchRelationships(query);
  +		prefetchRelationships(query);
   	}
   
   
  -    /**
  -     * read all objects of this iterator. objects will be placed in cache
  -     */ 
  +	/**
  +	 * read all objects of this iterator. objects will be placed in cache
  +	 */
   	private Collection getOwnerObjects()
   	{
   		Collection owners = new Vector();
  @@ -270,73 +266,73 @@
   		return owners;
   	}
   
  -    /**
  -     * prefetch defined relationships 
  -     * requires JDBC level 2.0, does not work with Arrays
  -     */ 
  +	/**
  +	 * prefetch defined relationships
  +	 * requires JDBC level 2.0, does not work with Arrays
  +	 */
   	private void prefetchRelationships(Query query)
   	{
  -        List prefetchedRel;
  +		List prefetchedRel;
   		Collection owners;
  -        String relName;
  +		String relName;
   		RelationshipPrefetcher[] prefetchers;
   
  -		if (query == null || 
  -			query.getCriteria() == null ||
  -			query.getCriteria().getPrefetchedRelationships().isEmpty())
  +		if (query == null ||
  +				query.getCriteria() == null ||
  +				query.getCriteria().getPrefetchedRelationships().isEmpty())
   		{
   			return;
   		}
   
  -        if (!supportsAdvancedJDBCCursorControl())
  -        {
  -            logger.info("prefetching relationships requires JDBC level 2.0");    
  -            return;
  -        }      
  +		if (!supportsAdvancedJDBCCursorControl())
  +		{
  +			logger.info("prefetching relationships requires JDBC level 2.0");
  +			return;
  +		}
   
  -        // prevent releasing of DBResources
  -        inBatchedMode = true;
  +		// prevent releasing of DBResources
  +		inBatchedMode = true;
   
   		prefetchedRel = query.getCriteria().getPrefetchedRelationships();
   		prefetchers = new RelationshipPrefetcher[prefetchedRel.size()];
   
  -        // disable auto retrieve for all prefetched relationships
  +		// disable auto retrieve for all prefetched relationships
   		for (int i = 0; i < prefetchedRel.size(); i++)
   		{
  -            relName = (String) prefetchedRel.get(i);
  -            prefetchers[i] = RelationshipPrefetcherFactory.createRelationshipPrefetcher(m_broker,
m_cld, relName);
  -            prefetchers[i].prepareRelationshipSettings();
  -		}
  -
  -        // materialize ALL owners of this Iterator
  -        owners = getOwnerObjects();
  -
  -        // prefetch relationships and associate with owners
  -        for (int i = 0; i < prefetchedRel.size(); i++)
  -        {
  -        	prefetchers[i].prefetchRelationship(owners);
  -        }
  -
  -        // reset auto retrieve for all prefetched relationships
  -        for (int i = 0; i < prefetchedRel.size(); i++)
  -        {
  -            prefetchers[i].restoreRelationshipSettings();
  -        }
  +			relName = (String) prefetchedRel.get(i);
  +			prefetchers[i] = RelationshipPrefetcherFactory.createRelationshipPrefetcher(m_broker,
m_cld, relName);
  +			prefetchers[i].prepareRelationshipSettings();
  +		}
  +
  +		// materialize ALL owners of this Iterator
  +		owners = getOwnerObjects();
  +
  +		// prefetch relationships and associate with owners
  +		for (int i = 0; i < prefetchedRel.size(); i++)
  +		{
  +			prefetchers[i].prefetchRelationship(owners);
  +		}
  +
  +		// reset auto retrieve for all prefetched relationships
  +		for (int i = 0; i < prefetchedRel.size(); i++)
  +		{
  +			prefetchers[i].restoreRelationshipSettings();
  +		}
   
   		try
   		{
  -			m_rsAndStmt.m_rs.beforeFirst(); // reposition resultset jdbc 2.0  
  +			m_rsAndStmt.m_rs.beforeFirst(); // reposition resultset jdbc 2.0
   		}
   		catch (SQLException e)
   		{
  -            logger.error("beforeFirst failed !",e);
  +			logger.error("beforeFirst failed !", e);
   		}
   
  -        inBatchedMode = false;
  -        hasCalledCheck = false;
  +		inBatchedMode = false;
  +		hasCalledCheck = false;
   
   	}
  -        
  +
   	/**
   	 * returns an Identity object representing the current resultset row
   	 */
  @@ -403,28 +399,28 @@
   				// result may still be null!
   				if (result != null)
   				{
  -                   /*
  -                    * synchronize on result so the ODMG-layer can take a snapshot only
of
  -                    * fully cached (i.e. with all references + collections) objects
  -                    */
  -                    synchronized(result)
  -                    {
  -					   cache.cache(oid, result);
  -				           LoadedObjectsRegistry.register(result);
  -					   /**
  -					   * MBAIRD
  -					   * if you have multiple classes mapped to a table, and you query on the base class
  -					   * you could get back NON base class objects, so we shouldn't pass m_cld, but rather
  -					   * the class descriptor for the actual class.
  -					   */
  -					   // fill reference and collection attributes
  -					   ClassDescriptor cld = m_cld.getRepository().getDescriptorFor(result.getClass());
  -					   // don't force loading of reference
  -					   final boolean unforced = false;
  -					   m_broker.retrieveReferences(result, cld, unforced);
  -					   m_broker.retrieveCollections(result, cld, unforced);
  -				    }
  -                }
  +					/*
  +					 * synchronize on result so the ODMG-layer can take a snapshot only of
  +					 * fully cached (i.e. with all references + collections) objects
  +					 */
  +					synchronized (result)
  +					{
  +						cache.cache(oid, result);
  +						LoadedObjectsRegistry.register(result);
  +						/**
  +						 * MBAIRD
  +						 * if you have multiple classes mapped to a table, and you query on the base class
  +						 * you could get back NON base class objects, so we shouldn't pass m_cld, but rather
  +						 * the class descriptor for the actual class.
  +						 */
  +						// fill reference and collection attributes
  +						ClassDescriptor cld = m_cld.getRepository().getDescriptorFor(result.getClass());
  +						// don't force loading of reference
  +						final boolean unforced = false;
  +						m_broker.retrieveReferences(result, cld, unforced);
  +						m_broker.retrieveCollections(result, cld, unforced);
  +					}
  +				}
   			}
   			else
   			{
  @@ -470,58 +466,80 @@
   	}
   
   	/**
  -	 * Answer the counted size
	 * @return int
	 */
  +	 * Answer the counted size
  +	 * @return int
  +	 */
   	protected int countedSize() throws PersistenceBrokerException
   	{
   		return m_broker.getCount(m_query);
   	}
  -			
  +
   	/**
   	 *
   	 * @return the size of the iterator, aka the number of rows in this iterator.
   	 */
  -        public int size() throws PersistenceBrokerException {
  -            int retval = 0; // default size is 0;
  -            if (!supportsAdvancedJDBCCursorControl() || PlatformFactory.getPlatformFor(m_cld.getConnectionDescriptor()).useCountForResultsetSize()
) {
  -                /**
  -                 * MBAIRD: doesn't support the .last .getRow method, use the .getCount
on the
  -                 * persistenceBroker which executes a count(*) query.
  -                 */
  -                if (logger.isDebugEnabled()) logger.debug("Executing count(*) to get size()");
  -                retval = countedSize();
  -            }
  -            else {
  -                /**
  -                 * Use the .last .getRow method of finding size.
  -                 * The reason for supplying an alternative method is effeciency,
  -                 * some driver/db combos are a lot more efficient at just moving the cursor
  -                 * and returning the row in a real (not -1) number.
  -                 */
  -                int whereIAm = 1; // first
  -                try {
  -                    if (m_rsAndStmt.m_rs != null) {
  -                        whereIAm = m_rsAndStmt.m_rs.getRow();
  -                        if (m_rsAndStmt.m_rs.last()) {
  -                            retval = m_rsAndStmt.m_rs.getRow();
  -                        }
  -                        else {
  -                            retval = 0;
  -                        }
  -                        // go back from whence I came.
  -                        if (whereIAm > 0) {
  -                            m_rsAndStmt.m_rs.absolute(whereIAm);
  -                        }
  -                        else {
  -                            m_rsAndStmt.m_rs.beforeFirst();
  -                        }
  -                    }
  -                }
  -                catch (SQLException se) {
  -                    advancedJDBCSupport = false;
  -                }
  -            }
  -            return retval;
  -        }
  +	public int size() throws PersistenceBrokerException
  +	{
  +		int retval = 0; // default size is 0;
  +		boolean forwardOnly = true;
  +		try
  +		{
  +			forwardOnly = m_rsAndStmt.m_stmt.getResultSetType() == ResultSet.TYPE_FORWARD_ONLY;
  +		}
  +		catch (SQLException e)
  +		{
  +		}
  +		if (!supportsAdvancedJDBCCursorControl()
  +			|| PlatformFactory.getPlatformFor(m_cld.getConnectionDescriptor()).useCountForResultsetSize()
  +			|| forwardOnly)
  +		{
  +			/**
  +			 * MBAIRD: doesn't support the .last .getRow method, use the .getCount on the
  +			 * persistenceBroker which executes a count(*) query.
  +			 */
  +			if (logger.isDebugEnabled()) logger.debug("Executing count(*) to get size()");
  +			retval = countedSize();
  +		}
  +		else
  +		{
  +			/**
  +			 * Use the .last .getRow method of finding size.
  +			 * The reason for supplying an alternative method is effeciency,
  +			 * some driver/db combos are a lot more efficient at just moving the cursor
  +			 * and returning the row in a real (not -1) number.
  +			 */
  +			int whereIAm = 1; // first
  +			try
  +			{
  +				if (m_rsAndStmt.m_rs != null)
  +				{
  +					whereIAm = m_rsAndStmt.m_rs.getRow();
  +					if (m_rsAndStmt.m_rs.last())
  +					{
  +						retval = m_rsAndStmt.m_rs.getRow();
  +					}
  +					else
  +					{
  +						retval = 0;
  +					}
  +					// go back from whence I came.
  +					if (whereIAm > 0)
  +					{
  +						m_rsAndStmt.m_rs.absolute(whereIAm);
  +					}
  +					else
  +					{
  +						m_rsAndStmt.m_rs.beforeFirst();
  +					}
  +				}
  +			}
  +			catch (SQLException se)
  +			{
  +				advancedJDBCSupport = false;
  +			}
  +		}
  +		return retval;
  +	}
   
   	/**
   	 * Moves the cursor to the given row number in the iterator.
  @@ -539,8 +557,8 @@
   				if (m_rsAndStmt.m_rs != null)
   				{
   					retval = m_rsAndStmt.m_rs.absolute(row);
  -                                        m_current_row = row;
  -                                        hasCalledCheck = false;
  +					m_current_row = row;
  +					hasCalledCheck = false;
   				}
   			}
   			catch (SQLException e)
  @@ -550,27 +568,37 @@
   		}
   		else
   		{
  -                    if(row>m_current_row){
  -                        try{                        
  -                            while(m_current_row<row && m_rsAndStmt.m_rs.next()
){
  -                                m_current_row++;
  -                            }
  -                            if(m_current_row == row){
  -                                retval = true;
  -                            }else{
  -                                hasCalledCheck = true;
  -                                hasNext = false;
  -                                retval = false;
  -                                releaseDbResources();
  -                            }
  -                        }catch(Exception ex){
  -                            hasCalledCheck = true;
  -                            hasNext = false;
  -                            retval = false;
  -                        }
  -                    }else{
  -			logger.info("Your driver does not support advanced JDBC Functionality, you cannot call
absolute() with a position < current");
  -                    }
  +			if (row > m_current_row)
  +			{
  +				try
  +				{
  +					while (m_current_row < row && m_rsAndStmt.m_rs.next())
  +					{
  +						m_current_row++;
  +					}
  +					if (m_current_row == row)
  +					{
  +						retval = true;
  +					}
  +					else
  +					{
  +						hasCalledCheck = true;
  +						hasNext = false;
  +						retval = false;
  +						releaseDbResources();
  +					}
  +				}
  +				catch (Exception ex)
  +				{
  +					hasCalledCheck = true;
  +					hasNext = false;
  +					retval = false;
  +				}
  +			}
  +			else
  +			{
  +				logger.info("Your driver does not support advanced JDBC Functionality, you cannot call
absolute() with a position < current");
  +			}
   		}
   		return retval;
   	}
  @@ -591,7 +619,7 @@
   				if (m_rsAndStmt.m_rs != null)
   				{
   					retval = m_rsAndStmt.m_rs.relative(row);
  -                                        m_current_row += row;
  +					m_current_row += row;
   				}
   			}
   			catch (SQLException e)
  @@ -599,16 +627,16 @@
   				advancedJDBCSupport = false;
   			}
   		}
  -		else                    
  +		else
   		{
  -                    if (row >= 0)
  -                    {
  -                        return absolute(m_current_row + row);
  -                    }
  -                    else
  -                    {
  -			logger.info("Your driver does not support advanced JDBC Functionality, you cannot call
relative() with a negative value");
  -                    }
  +			if (row >= 0)
  +			{
  +				return absolute(m_current_row + row);
  +			}
  +			else
  +			{
  +				logger.info("Your driver does not support advanced JDBC Functionality, you cannot call
relative() with a negative value");
  +			}
   		}
   		return retval;
   	}
  @@ -621,17 +649,17 @@
   	 */
   	public void releaseDbResources()
   	{
  -        if (!inBatchedMode)     // resources are reused in batched mode 
  -        {
  -		  m_broker.getStatementManager().closeResources(m_rsAndStmt.m_stmt, m_rsAndStmt.m_rs);
  -        }  
  +		if (!inBatchedMode)     // resources are reused in batched mode
  +		{
  +			m_broker.getStatementManager().closeResources(m_rsAndStmt.m_stmt, m_rsAndStmt.m_rs);
  +		}
   	}
  -	
  +
   	/**
   	 * Return the DescriptorRepository
  -	 */ 
  +	 */
   	protected DescriptorRepository getDescriptorRepository()
   	{
   		return m_broker.getDescriptorRepository();
  -	}	
  +	}
   }
  
  
  

Mime
View raw message