001/* 002 * Copyright 2002-2016 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.jdbc.object; 018 019import java.util.Map; 020 021import org.springframework.beans.BeanUtils; 022import org.springframework.jdbc.core.RowMapper; 023import org.springframework.util.Assert; 024 025/** 026 * A concrete variant of {@link SqlQuery} which can be configured 027 * with a {@link RowMapper}. 028 * 029 * @author Thomas Risberg 030 * @author Juergen Hoeller 031 * @since 3.0 032 * @see #setRowMapper 033 * @see #setRowMapperClass 034 */ 035public class GenericSqlQuery<T> extends SqlQuery<T> { 036 037 private RowMapper<T> rowMapper; 038 039 @SuppressWarnings("rawtypes") 040 private Class<? extends RowMapper> rowMapperClass; 041 042 043 /** 044 * Set a specific {@link RowMapper} instance to use for this query. 045 * @since 4.3.2 046 */ 047 public void setRowMapper(RowMapper<T> rowMapper) { 048 this.rowMapper = rowMapper; 049 } 050 051 /** 052 * Set a {@link RowMapper} class for this query, creating a fresh 053 * {@link RowMapper} instance per execution. 054 */ 055 @SuppressWarnings("rawtypes") 056 public void setRowMapperClass(Class<? extends RowMapper> rowMapperClass) { 057 this.rowMapperClass = rowMapperClass; 058 } 059 060 @Override 061 public void afterPropertiesSet() { 062 super.afterPropertiesSet(); 063 Assert.isTrue(this.rowMapper != null || this.rowMapperClass != null, 064 "'rowMapper' or 'rowMapperClass' is required"); 065 } 066 067 068 @Override 069 @SuppressWarnings("unchecked") 070 protected RowMapper<T> newRowMapper(Object[] parameters, Map<?, ?> context) { 071 return (this.rowMapper != null ? this.rowMapper : BeanUtils.instantiateClass(this.rowMapperClass)); 072 } 073 074}