001 /* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 package org.apache.commons.dbutils.handlers; 018 019 import java.sql.ResultSet; 020 import java.sql.SQLException; 021 022 import org.apache.commons.dbutils.ResultSetHandler; 023 import org.apache.commons.dbutils.RowProcessor; 024 025 /** 026 * <code>ResultSetHandler</code> implementation that converts the first 027 * <code>ResultSet</code> row into a JavaBean. This class is thread safe. 028 * 029 * @see org.apache.commons.dbutils.ResultSetHandler 030 */ 031 public class BeanHandler implements ResultSetHandler { 032 033 /** 034 * The Class of beans produced by this handler. 035 */ 036 private final Class type; 037 038 /** 039 * The RowProcessor implementation to use when converting rows 040 * into beans. 041 */ 042 private final RowProcessor convert; 043 044 /** 045 * Creates a new instance of BeanHandler. 046 * 047 * @param type The Class that objects returned from <code>handle()</code> 048 * are created from. 049 */ 050 public BeanHandler(Class type) { 051 this(type, ArrayHandler.ROW_PROCESSOR); 052 } 053 054 /** 055 * Creates a new instance of BeanHandler. 056 * 057 * @param type The Class that objects returned from <code>handle()</code> 058 * are created from. 059 * @param convert The <code>RowProcessor</code> implementation 060 * to use when converting rows into beans. 061 */ 062 public BeanHandler(Class type, RowProcessor convert) { 063 this.type = type; 064 this.convert = convert; 065 } 066 067 /** 068 * Convert the first row of the <code>ResultSet</code> into a bean with the 069 * <code>Class</code> given in the constructor. 070 * 071 * @return An initialized JavaBean or <code>null</code> if there were no 072 * rows in the <code>ResultSet</code>. 073 * 074 * @throws SQLException if a database access error occurs 075 * @see org.apache.commons.dbutils.ResultSetHandler#handle(java.sql.ResultSet) 076 */ 077 public Object handle(ResultSet rs) throws SQLException { 078 return rs.next() ? this.convert.toBean(rs, this.type) : null; 079 } 080 081 }