001/*
002 * Copyright 2002-2018 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.lang.Nullable;
024import org.springframework.util.Assert;
025
026/**
027 * A concrete variant of {@link SqlQuery} which can be configured
028 * with a {@link RowMapper}.
029 *
030 * @author Thomas Risberg
031 * @author Juergen Hoeller
032 * @since 3.0
033 * @param <T> the result type
034 * @see #setRowMapper
035 * @see #setRowMapperClass
036 */
037public class GenericSqlQuery<T> extends SqlQuery<T> {
038
039        @Nullable
040        private RowMapper<T> rowMapper;
041
042        @SuppressWarnings("rawtypes")
043        @Nullable
044        private Class<? extends RowMapper> rowMapperClass;
045
046
047        /**
048         * Set a specific {@link RowMapper} instance to use for this query.
049         * @since 4.3.2
050         */
051        public void setRowMapper(RowMapper<T> rowMapper) {
052                this.rowMapper = rowMapper;
053        }
054
055        /**
056         * Set a {@link RowMapper} class for this query, creating a fresh
057         * {@link RowMapper} instance per execution.
058         */
059        @SuppressWarnings("rawtypes")
060        public void setRowMapperClass(Class<? extends RowMapper> rowMapperClass) {
061                this.rowMapperClass = rowMapperClass;
062        }
063
064        @Override
065        public void afterPropertiesSet() {
066                super.afterPropertiesSet();
067                Assert.isTrue(this.rowMapper != null || this.rowMapperClass != null,
068                                "'rowMapper' or 'rowMapperClass' is required");
069        }
070
071
072        @Override
073        @SuppressWarnings("unchecked")
074        protected RowMapper<T> newRowMapper(@Nullable Object[] parameters, @Nullable Map<?, ?> context) {
075                if (this.rowMapper != null) {
076                        return this.rowMapper;
077                }
078                else {
079                        Assert.state(this.rowMapperClass != null, "No RowMapper set");
080                        return BeanUtils.instantiateClass(this.rowMapperClass);
081                }
082        }
083
084}