baliuka 2003/03/16 08:23:48 Modified: dbutils/src/java/org/apache/commons/dbutils DbUtils.java MapHandler.java ProcedureUtils.java dbutils/src/test/org/apache/commons/dbutils Demo.java ProcedureUtilsTest.java Added: dbutils/src/java/org/apache/commons/dbutils BeanCollectionHandler.java BeanHandler.java Log: adde support for beans Revision Changes Path 1.21 +142 -75 jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/DbUtils.java Index: DbUtils.java =================================================================== RCS file: /home/cvs/jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/DbUtils.java,v retrieving revision 1.20 retrieving revision 1.21 diff -u -r1.20 -r1.21 --- DbUtils.java 16 Mar 2003 14:00:15 -0000 1.20 +++ DbUtils.java 16 Mar 2003 16:23:47 -0000 1.21 @@ -68,17 +68,17 @@ static{ - DEFAULTS.put(int.class, new Integer(0)); - DEFAULTS.put(short.class, new Short((short)0)); - DEFAULTS.put(byte.class, new Byte((byte)0)); - DEFAULTS.put(float.class, new Float(0f)); - DEFAULTS.put(double.class, new Double(0.0)); - DEFAULTS.put(long.class, new Long(0L)); - DEFAULTS.put(boolean.class, Boolean.FALSE); - DEFAULTS.put(char.class, new Character('\u0000')); - + DEFAULTS.put(int.class, new Integer(0)); + DEFAULTS.put(short.class, new Short((short)0)); + DEFAULTS.put(byte.class, new Byte((byte)0)); + DEFAULTS.put(float.class, new Float(0f)); + DEFAULTS.put(double.class, new Double(0.0)); + DEFAULTS.put(long.class, new Long(0L)); + DEFAULTS.put(boolean.class, Boolean.FALSE); + DEFAULTS.put(char.class, new Character('\u0000')); + } - + public static abstract class ListAdapter extends ArrayList implements ResultSetHandler{ public final Object handle(java.sql.ResultSet rs, Object[] params, Object userObject) throws java.sql.SQLException{ @@ -141,13 +141,13 @@ } - public static Object executeQuery(Connection connection, String query, - Object[] vals, ResultSetHandler rsh, ResultSetMetaDataHandler rsmdh) throws SQLException{ - return executeQuery(connection,query, vals, rsh, rsmdh, null ); -} + public static Object executeQuery(Connection connection, String query, + Object[] vals, ResultSetHandler rsh, ResultSetMetaDataHandler rsmdh) throws SQLException{ + return executeQuery(connection,query, vals, rsh, rsmdh, null ); + } - public static Object executeQuery(Connection connection, String query, - Object[] vals, ResultSetHandler rsh, ResultSetMetaDataHandler rsmdh, Object userObject) + public static Object executeQuery(Connection connection, String query, + Object[] vals, ResultSetHandler rsh, ResultSetMetaDataHandler rsmdh, Object userObject) throws SQLException { PreparedStatement stmt = null; @@ -183,15 +183,15 @@ } static void rethrow(SQLException cause, String sql,Object[] vals )throws SQLException{ - - StringBuffer msg = - new StringBuffer(cause.getMessage() + " in query " + sql); + + StringBuffer msg = + new StringBuffer(cause.getMessage() + " in query " + sql); if (vals != null) { msg.append(java.util.Arrays.asList(vals).toString()); } SQLException newsqle = new SQLException(msg.toString()); - newsqle.setNextException(cause); - throw newsqle; + newsqle.setNextException(cause); + throw newsqle; } @@ -229,8 +229,8 @@ } - public static List executeListQuery(Connection connection, - String query, Object[] vals, Object userObject ) + public static List executeListQuery(Connection connection, + String query, Object[] vals, Object userObject ) throws SQLException { return executeListQuery(connection, query, vals, null, userObject); } @@ -241,8 +241,8 @@ * inside an List. * Null values in the Object array will be passed to the driver. */ - public static List executeListQuery(Connection connection, - String query, Object[] vals, ResultSetMetaDataHandler rsmdh, Object userObject ) + public static List executeListQuery(Connection connection, + String query, Object[] vals, ResultSetMetaDataHandler rsmdh, Object userObject ) throws SQLException { return (List)executeQuery(connection,query,vals, @@ -253,7 +253,7 @@ } } - + , rsmdh , userObject ); @@ -301,68 +301,135 @@ return false; } } - - /** + + /** * Create an Map from a ResultSet. * It is assumed that next() has already been called on the ResultSet. */ - + public static java.util.Map resultSetToMap(ResultSet rs) throws SQLException { - java.util.Map result = new java.util.Hashtable(); - ResultSetMetaData rsmd = rs.getMetaData(); - int cnt = rsmd.getColumnCount(); - for( int i = 1; i <= cnt; i++ ){ + java.util.Map result = new java.util.Hashtable(); + ResultSetMetaData rsmd = rs.getMetaData(); + int cnt = rsmd.getColumnCount(); + for( int i = 1; i <= cnt; i++ ){ Object value = rs.getObject(i); if(!rs.wasNull()){ - result.put(rsmd.getColumnName(i),value); + result.put(rsmd.getColumnName(i),value); } - } - return result; + } + return result; } /** * Create an Bean from a ResultSet. * It is assumed that next() has already been called on the ResultSet. */ - - public static Object resultSetToBean(ResultSet rs, Object obj) throws SQLException { - - try{ - - java.beans.BeanInfo bInfo = java.beans.Introspector.getBeanInfo( - obj.getClass()); - java.beans.PropertyDescriptor pd[] = bInfo.getPropertyDescriptors(); - - ResultSetMetaData rsmd = rs.getMetaData(); - int cnt = rsmd.getColumnCount(); - LOOP: - for( int i = 1; i <= cnt; i++ ){ - String name = rsmd.getColumnName(i); - for( int j = 0; j < pd.length; j++ ){ - if(name.equals(pd[j].getName())){ - Object value = rs.getObject(i); - if(!rs.wasNull() && pd[j].getPropertyType().isPrimitive() ){ - value = DEFAULTS.get( pd[j].getPropertyType() ); - } - try{ - - pd[j].getWriteMethod().invoke(obj, new Object[]{ value }); - - }catch(Exception e){ - throw new DbException( "can not set " + name , e); - } - continue LOOP; - } - } - throw new SQLException(name + " not found in " + obj.getClass().getName() ); - } - }catch(java.beans.IntrospectionException ie){ - throw new DbException(ie); - } - return obj; + public static Object resultSetToBean(ResultSet rs, Object obj) throws SQLException { + + try{ + + java.beans.BeanInfo bInfo = java.beans.Introspector.getBeanInfo( + obj.getClass()); + java.beans.PropertyDescriptor pd[] = bInfo.getPropertyDescriptors(); + + ResultSetMetaData rsmd = rs.getMetaData(); + int cnt = rsmd.getColumnCount(); + LOOP: + for( int i = 1; i <= cnt; i++ ){ + String name = rsmd.getColumnName(i); + for( int j = 0; j < pd.length; j++ ){ + if(name.equals(pd[j].getName())){ + Object value = rs.getObject(i); + if( rs.wasNull() && pd[j].getPropertyType().isPrimitive() ){ + value = DEFAULTS.get( pd[j].getPropertyType() ); + } + try{ + + pd[j].getWriteMethod().invoke(obj, new Object[]{ value }); + continue LOOP; + + }catch(Exception e){ + throw new DbException( "can not set " + name , e); + } + + } + } + throw new SQLException(name + " not found in " + obj.getClass().getName() ); + } + }catch(java.beans.IntrospectionException ie){ + throw new DbException(ie); + } + + return obj; } /** + * optimized for collections of beans + * + */ + public static java.util.Collection resultSetToBeanCollection(ResultSet rs, Class cls) throws SQLException { + java.util.List results = new java.util.Vector(); + try{ + + if(rs.next()){ + + java.beans.BeanInfo bInfo = java.beans.Introspector.getBeanInfo(cls); + java.beans.PropertyDescriptor pd[] = bInfo.getPropertyDescriptors(); + ResultSetMetaData rsmd = rs.getMetaData(); + int cnt = rsmd.getColumnCount(); + int nameToIndex[] = new int[ cnt + 1 ]; + + LOOP: + for( int i = 1; i <= cnt; i++ ){ + for( int j = 0; j < pd.length; j++ ){ + String name = rsmd.getColumnName(i); + if(name.equals(pd[i].getName())){ + nameToIndex[i] = j; + continue LOOP; + } + } + throw new SQLException(" index not found for " + pd[i].getName() ); + } + do{ + + Object obj; + try{ + + obj = cls.newInstance(); + + }catch(Exception e){ + throw new DbException( "can not create " + cls.getName() , e); + } + + for(int i = 1; i < cnt; i++){ + Object value = rs.getObject(i); + int index = nameToIndex[i]; + if( rs.wasNull() && pd[index].getPropertyType().isPrimitive() ){ + value = DEFAULTS.get( pd[index].getPropertyType() ); + } + try{ + + pd[i].getWriteMethod().invoke(obj, new Object[]{ value }); + + + }catch(Exception e){ + throw new DbException( "can not set " + pd[index].getName() , e); + } + } + results.add(obj); + }while(rs.next()); + } + + }catch(java.beans.IntrospectionException ie){ + throw new DbException(ie); + } + + + return results; + } + + + /** * Create an Object array from a ResultSet. * It is assumed that next() has already been called on the ResultSet. */ @@ -428,7 +495,7 @@ } rs.close(); } - + /** * Close a connection, avoid closing if null and hide * any exceptions that occur. @@ -464,9 +531,9 @@ // quiet } } - + /** - * Close a connection, statement and resultset, avoiding + * Close a connection, statement and resultset, avoiding * closing if null and hiding any exceptions that occur. */ public static void closeQuietly(Connection conn, Statement stmt, ResultSet rs) { 1.2 +1 -1 jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/MapHandler.java Index: MapHandler.java =================================================================== RCS file: /home/cvs/jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/MapHandler.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- MapHandler.java 16 Mar 2003 13:28:53 -0000 1.1 +++ MapHandler.java 16 Mar 2003 16:23:47 -0000 1.2 @@ -8,7 +8,7 @@ */ public class MapHandler implements ResultSetHandler { - /** Creates a new instance of VectorHandler */ + /** Creates a new instance of MapHandler */ public MapHandler() { } 1.12 +220 -184 jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/ProcedureUtils.java Index: ProcedureUtils.java =================================================================== RCS file: /home/cvs/jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/ProcedureUtils.java,v retrieving revision 1.11 retrieving revision 1.12 diff -u -r1.11 -r1.12 --- ProcedureUtils.java 16 Mar 2003 13:28:53 -0000 1.11 +++ ProcedureUtils.java 16 Mar 2003 16:23:47 -0000 1.12 @@ -179,8 +179,8 @@ ProcedureDescriptor descriptor = new ProcedureDescriptor(); Object textArgs[] = new Object[proc.getParameterTypes().length]; Arrays.fill(textArgs,""); - descriptor.dynamic = !sb.toString().equals( - MessageFormat.format(sb.toString(),textArgs) ); + descriptor.dynamic = !sb.toString().equals( + MessageFormat.format(sb.toString(),textArgs) ); if(indexes.size() > 0){ @@ -204,27 +204,27 @@ return descriptor; } - + private static boolean isCollection(Class cls){ - - return cls.isAssignableFrom(Collection.class); - } - + + return cls.isAssignableFrom(Collection.class); + } + private static boolean isMap(Class cls){ - - return cls.isAssignableFrom(Map.class); - } - - private static boolean isVector(Class cls){ - - return cls.isArray() && ! cls.getComponentType().isPrimitive(); - } + + return cls.isAssignableFrom(Map.class); + } - private static boolean isScalar(Class cls){ + private static boolean isVector(Class cls){ + + return cls.isArray() && ! cls.getComponentType().isPrimitive(); + } + private static boolean isScalar(Class cls){ + return cls.isPrimitive() || Number.class.isAssignableFrom(cls) || - Character.class == cls || String.class == cls || - Boolean.class == cls || java.util.Date.class.isAssignableFrom(cls); + Character.class == cls || String.class == cls || + Boolean.class == cls || java.util.Date.class.isAssignableFrom(cls); } @@ -232,30 +232,68 @@ Method methods[] = cls.getDeclaredMethods(); LOOP: - for(int i=0; i< methods.length; i++ ){ - - if(methods[i].getName().equals(jmethod.getName()) ){ - - JavaParameter jparams[] = jmethod.getParameters(); - Class params[] = methods[i].getParameterTypes(); + for(int i=0; i< methods.length; i++ ){ - if( params.length == jparams.length ){ + if(methods[i].getName().equals(jmethod.getName()) ){ - for( int j = 0; j < params.length; j++ ){ + JavaParameter jparams[] = jmethod.getParameters(); + Class params[] = methods[i].getParameterTypes(); + + if( params.length == jparams.length ){ - if(!params[j].getName().equals(jparams[j].getType().getValue()) ){ - continue LOOP; + for( int j = 0; j < params.length; j++ ){ + + if(!params[j].getName().equals(jparams[j].getType().getValue()) ){ + continue LOOP; + } + } + return methods[i]; } - return methods[i]; } + } + + throw new IllegalStateException("metadata not found for " + jmethod); + } + + static Class resolve(ClassLoader loader,String imports[], String name){ + + String names[] = { + name, + "org.apache.commons.dbutils." + name + }; + + + for(int i = 0; i < names.length; i++){ + + try{ + + return loader.loadClass(names[i]); + + }catch(ClassNotFoundException cnfe){ + + } + + } + for(int i = 0; i < imports.length; i++){ + + try{ + if(imports[i].endsWith( name )){ + return loader.loadClass(imports[i]); + }else if(imports[i].endsWith("*")){ + + return loader.loadClass( + imports[i].substring(0,imports[i].length() - 1 ) + name); + } + + }catch(ClassNotFoundException cnfe){ } } - throw new IllegalStateException("metadata not found for " + jmethod); + return null; } static ResultSetHandler findHandler(Method method, JavaMethod jmethod){ @@ -264,6 +302,18 @@ ResultSetHandler handler = null; String name = null; + + String imports[] = jmethod.getParentClass(). + getParentSource().getImports(); + + Set set = new java.util.HashSet(); + set.addAll( Arrays.asList(imports) ); + set.add(jmethod.getParentClass().getPackage() + ".*"); + + imports = (String[])set.toArray(new String[]{}); + + ClassLoader loader = method.getDeclaringClass().getClassLoader(); + DocletTag tag = jmethod.getTagByName(HANDLER_TAG); @@ -273,6 +323,24 @@ name = (name == null || name.trim().length() == 0 ? null : name.trim() ); } + if( "bean".equals( name ) ){ + + return new BeanHandler(method.getReturnType()); + } + + if( name != null && name.startsWith("beans") && isCollection(method.getReturnType()) ){ + java.util.StringTokenizer st = new java.util.StringTokenizer(name,"() \t"); + st.nextToken(); + if(st.hasMoreElements()){ + Class cls = resolve(loader,imports,st.nextToken()); + if(cls != null){ + return new BeanCollectionHandler(cls); + } + } + } + + + handler = (ResultSetHandler)PREDEFINED_HANDLERS.get(name); if(name != null && handler != null ){ @@ -300,57 +368,20 @@ return MAP_HANDLER; } - - - - if(name != null){ - String imports[] = jmethod.getParentClass(). - getParentSource().getImports(); - String names[] = { - name, - jmethod.getParentClass().getPackage() + "." + name, - "org.apache.commons.dbutils." + name - }; - - - ClassLoader loader = method.getDeclaringClass().getClassLoader(); - - try{ - - for(int i = 0; i < names.length; i++){ - - try{ - - return (ResultSetHandler)loader.loadClass(names[i]).newInstance(); - - }catch(ClassNotFoundException cnfe){ - - } - - } - for(int i = 0; i < imports.length; i++){ - - try{ - if(imports[i].endsWith( name )){ - return (ResultSetHandler)loader.loadClass(imports[i]).newInstance(); - }else if(imports[i].endsWith("*")){ - - return (ResultSetHandler)loader.loadClass( - imports[i].substring(0,imports[i].length() - 1 ) + name).newInstance(); - } - - }catch(ClassNotFoundException cnfe){ - - } + try{ + if(name != null){ + Class cls = resolve(loader,imports,name); + if(cls != null){ + return (ResultSetHandler)cls.newInstance(); } - - }catch(Exception e){ - throw new IllegalStateException( e.getMessage() + ":" + name + - " not found for " + method ); } + }catch(Exception e){ + throw new IllegalStateException( e.getMessage() + ":" + name + + " not found for " + method ); } + throw new IllegalStateException( "Handler not found for " + method ); } @@ -387,69 +418,69 @@ } desctiptors.put( method, - compile( method, sql, handler, update, + compile( method, sql, handler, update, jmethods[i].getTagByName(CACHE_TAG) != null, jmethods[i].getTagByName(FLUSH_TAG) != null - ) + ) ); } return desctiptors; } - + static Object convert( Class to, Object from, Method forErrorReport ){ if( from == null ){ - if(to.isPrimitive()){ - throw new IllegalStateException("can not convert null to primitive as return value in " + - forErrorReport - ); - }else{ - return null; - } - + if(to.isPrimitive()){ + throw new IllegalStateException("can not convert null to primitive as return value in " + + forErrorReport + ); + }else{ + return null; + } + } if( to.isAssignableFrom(from.getClass()) ){ - return from; - + return from; + }else{ - - if(to.isPrimitive() && - ( ( from instanceof Number ) || - from.getClass() == Boolean.class || - from.getClass() == Character.class ) ){ + if(to.isPrimitive() && + ( ( from instanceof Number ) || + from.getClass() == Boolean.class || + from.getClass() == Character.class ) ){ + return from; } - throw new IllegalStateException("can not convert " + from.getClass().getName() - + " to " + to.getName() + " as return value in " + - forErrorReport + throw new IllegalStateException("can not convert " + from.getClass().getName() + + " to " + to.getName() + " as return value in " + + forErrorReport ); - + } - + } public static void flush(Object procedures){ - + Invocation inv = (Invocation)Proxy.getInvocationHandler(procedures); inv.CACHE.clear(); } public static Connection getConnection(Object procedures){ - + Invocation inv = (Invocation)Proxy.getInvocationHandler(procedures); return inv.connection; } public static void connect(Object procedures, Connection connection){ - + Invocation inv = (Invocation)Proxy.getInvocationHandler(procedures); inv.connection = connection; } @@ -473,50 +504,50 @@ } static class CacheKey{ - Method method; - Object[] args; - int hash ; - - CacheKey( Method method, Object[] args ){ - this.method = method; - this.args = args; - hash = method.hashCode(); - for(int i=0; i< args.length; i++){ - hash += 3*(args[i] == null ? 0 : args[i].hashCode()); - } - - } - - public int hashCode(){ - return hash; - } - public boolean equals( Object obj ){ - if(obj != null && ( obj instanceof CacheKey)){ - - CacheKey key = (CacheKey)obj; - if(key.method == method || key.method.equals(method)){ - - for( int i = 0; i < args.length; i++ ){ - if( args[i] == key.args[i] ){ - continue; - } - if( args[i] == null || key.args[i] == null || - !args[i].equals(key.args[i]) ){ - return false; - } - } - return true; - + Method method; + Object[] args; + int hash ; + + CacheKey( Method method, Object[] args ){ + this.method = method; + this.args = args; + hash = method.hashCode(); + for(int i=0; i< args.length; i++){ + hash += 3*(args[i] == null ? 0 : args[i].hashCode()); + } + + } + + public int hashCode(){ + return hash; + } + public boolean equals( Object obj ){ + if(obj != null && ( obj instanceof CacheKey)){ + + CacheKey key = (CacheKey)obj; + if(key.method == method || key.method.equals(method)){ + + for( int i = 0; i < args.length; i++ ){ + if( args[i] == key.args[i] ){ + continue; + } + if( args[i] == null || key.args[i] == null || + !args[i].equals(key.args[i]) ){ + return false; + } + } + return true; + + }else{ + return false; + } + }else{ return false; } - - }else{ - return false; } - } - - + + } static class Invocation implements InvocationHandler{ @@ -535,8 +566,13 @@ int len = descriptor.indexMap.length; Object pargs[] = new Object[ len ]; for(int i = 0; i < len; i++ ){ - pargs[i] = args[ descriptor.indexMap[i] ]; + try{ + pargs[i] = args[ descriptor.indexMap[i] ]; + }catch(ArrayIndexOutOfBoundsException ae){ + throw new DbException( "parameter " + i +" out of range (" + descriptor.indexMap[i] + ")" ,ae); + } } + return pargs; } @@ -568,29 +604,29 @@ CacheKey key = null; Object value = null; if(descriptor.cached){ - key = new CacheKey(method,args); - value = CACHE.get(key); - if( value != null ){ - return value; - } - } + key = new CacheKey(method,args); + value = CACHE.get(key); + if( value != null ){ + return value; + } + } value = convert( method.getReturnType(), DbUtils.executeQuery( connection, descriptor.dynamic ? MessageFormat.format(descriptor.jdbcSQL,args) : descriptor.jdbcSQL, prepareArgs(descriptor,args), descriptor.handler, null,args ),method); - if(descriptor.cached && value != null){ - CACHE.put(key,value); - } - return value; + if(descriptor.cached && value != null){ + CACHE.put(key,value); + } + return value; }else{ int updateCount = DbUtils.executeUpdate( connection, descriptor.dynamic ? MessageFormat.format(descriptor.jdbcSQL,args) : descriptor.jdbcSQL, prepareArgs(descriptor,args) ); if(descriptor.flushOnExecute && updateCount > 0 ){ - CACHE.clear(); + CACHE.clear(); } if(method.getReturnType() == Void.TYPE ){ return null; @@ -636,97 +672,97 @@ private ReferenceQueue m_queue = new ReferenceQueue(); SoftRefMemoryCache(){ - this(256); + this(256); } - + /** * Creates new SoftRefMemoryCache * [EMAIL PROTECTED] map [EMAIL PROTECTED] maxStrongRefCount */ - SoftRefMemoryCache( int maxStrongRefCount) { - + SoftRefMemoryCache( int maxStrongRefCount) { + if (maxStrongRefCount < 0) { throw new java.lang.IllegalArgumentException(); } this.m_maxStrongRefCount = maxStrongRefCount; - + if (maxStrongRefCount > 0) { m_strongRefs = new Object[maxStrongRefCount]; } } - - + + /** * Get the object associated to the given unique key. * [EMAIL PROTECTED] key the Key Object [EMAIL PROTECTED] requested object or null */ - Object get(Object key) { + Object get(Object key) { removeSoftRef(); Object object = null; SoftRef ref = (SoftRef) m_map.get(key); - + if (ref != null) { object = ref.get(); } - + addStrongRef(object); return object; } - + /** * Cache the object associated to the given unique key. * [EMAIL PROTECTED] key the key object [EMAIL PROTECTED] object */ - void put(Object key, Object object) { + void put(Object key, Object object) { removeSoftRef(); internalStoreObject(key, object); } - + void clear(){ - removeSoftRef(); - if(m_map.size() > 0){ - m_map.clear(); - if(m_strongRefs != null){ - Arrays.fill(m_strongRefs, null); - } - } - } + removeSoftRef(); + if(m_map.size() > 0){ + m_map.clear(); + if(m_strongRefs != null){ + Arrays.fill(m_strongRefs, null); + } + } + } private SoftRef makeValue(Object key, Object value, ReferenceQueue queue) { return new SoftRef(key, value, queue); } - + // remove unused keys private void removeSoftRef() { SoftRef ref = (SoftRef) m_queue.poll(); - + while (ref != null) { m_map.remove(ref.key); ref = (SoftRef) m_queue.poll(); } } - + private void addStrongRef(Object object) { if (m_strongRefs != null) { m_strongRefs[(m_current++) % m_maxStrongRefCount] = object; } } - + private void internalStoreObject(Object key, Object object) { SoftRef ref = makeValue(key, object, m_queue); addStrongRef(ref.get()); m_map.put(key, ref); } - - final static class SoftRef extends SoftReference { - private Object key; - + + final static class SoftRef extends SoftReference { + private Object key; + private SoftRef(Object key, Object object, ReferenceQueue queue) { super(object, queue); this.key = key; 1.1 jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/BeanCollectionHandler.java Index: BeanCollectionHandler.java =================================================================== package org.apache.commons.dbutils; /** * * @author baliuka */ public class BeanCollectionHandler implements ResultSetHandler{ private Class type; /** Creates a new instance of BeanCollectionHandler */ public BeanCollectionHandler(Class type) { this.type = type; } public Object handle(java.sql.ResultSet rs, Object[] params, Object userObject) throws java.sql.SQLException { return DbUtils.resultSetToBeanCollection(rs,type); } } 1.1 jakarta-commons-sandbox/dbutils/src/java/org/apache/commons/dbutils/BeanHandler.java Index: BeanHandler.java =================================================================== package org.apache.commons.dbutils; import java.util.*; /** * * @author baliuka */ public class BeanHandler implements ResultSetHandler{ private Class type; /** Creates a new instance of BeanHandler */ public BeanHandler(Class type) { this.type = type; } public Object handle(java.sql.ResultSet rs, Object[] params, Object userObject) throws java.sql.SQLException { Object bean; if(rs.next()){ try{ bean = type.newInstance(); }catch(Exception e){ throw new DbException(e); } DbUtils.resultSetToBean(rs, bean); if(rs.next()){ throw new java.sql.SQLException(); } return bean; } throw new java.sql.SQLException(); } } 1.10 +13 -4 jakarta-commons-sandbox/dbutils/src/test/org/apache/commons/dbutils/Demo.java Index: Demo.java =================================================================== RCS file: /home/cvs/jakarta-commons-sandbox/dbutils/src/test/org/apache/commons/dbutils/Demo.java,v retrieving revision 1.9 retrieving revision 1.10 diff -u -r1.9 -r1.10 --- Demo.java 16 Mar 2003 13:28:53 -0000 1.9 +++ Demo.java 16 Mar 2003 16:23:48 -0000 1.10 @@ -57,19 +57,28 @@ */ public Map getRowAsMap( int id ); - /** [EMAIL PROTECTED] SELECT id, name FROM TBL WHERE ID=$1 [EMAIL PROTECTED] DemoBeanHandler */ public DemoBean getRowAsBean( DemoBean bean, int id ); + + /** + [EMAIL PROTECTED] SELECT id, name FROM TBL WHERE ID=$0 + [EMAIL PROTECTED] bean + */ + public DemoBean getRowAsBean( int id ); + + /** + [EMAIL PROTECTED] SELECT id, name FROM TBL + [EMAIL PROTECTED] beans(DemoBean) + */ + public java.util.Collection getBeans(); /** [EMAIL PROTECTED] SELECT * FROM {0} */ - public java.util.Collection getAll( String tbl ); - - + public java.util.Collection getAll( String tbl ); /** 1.9 +13 -0 jakarta-commons-sandbox/dbutils/src/test/org/apache/commons/dbutils/ProcedureUtilsTest.java Index: ProcedureUtilsTest.java =================================================================== RCS file: /home/cvs/jakarta-commons-sandbox/dbutils/src/test/org/apache/commons/dbutils/ProcedureUtilsTest.java,v retrieving revision 1.8 retrieving revision 1.9 diff -u -r1.8 -r1.9 --- ProcedureUtilsTest.java 16 Mar 2003 13:28:53 -0000 1.8 +++ ProcedureUtilsTest.java 16 Mar 2003 16:23:48 -0000 1.9 @@ -111,13 +111,16 @@ assertTrue( !demo.exists(1) ); assertTrue( demo.add(1,"test") == 1 ); assertTrue( demo.exists(1) ); + for( int i = 0; i< 10;i++){ demo.add(i + 2,"test" + i); } + demo.print(System.out); System.out.println("DYNAMIC SQL:"); demo.dynamicPrint(System.out,"TBL","ID",8); Integer max = demo.maxId("TBL"); + assertTrue( max != null ); assertTrue("cached query", max == demo.maxId("TBL") ); assertTrue( demo.now() != null ); @@ -125,10 +128,20 @@ assertTrue(demo.getRow(max.intValue()).length == 2 ); assertTrue(demo.getRowAsMap(max.intValue()).size() == 2 ); assertTrue(demo.getAll("TBL").size() > 2 ); + DemoBean bean = new DemoBean(); demo.getRowAsBean(bean, max.intValue()); assertTrue( bean.getId() == max.intValue() ); assertTrue( bean.getName() != null ); + + + bean = demo.getRowAsBean( max.intValue()); + assertTrue( bean.getId() == max.intValue() ); + assertTrue( bean.getName() != null ); + + Collection col = demo.getBeans(); + + assertTrue( col.size() == max.intValue() ); demo.clear();
--------------------------------------------------------------------- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]