001/* 002 * Copyright 2002-2020 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.datasource.init; 018 019import java.sql.Connection; 020 021import javax.sql.DataSource; 022 023import org.springframework.dao.DataAccessException; 024import org.springframework.jdbc.datasource.DataSourceUtils; 025import org.springframework.util.Assert; 026 027/** 028 * Utility methods for executing a {@link DatabasePopulator}. 029 * 030 * @author Juergen Hoeller 031 * @author Oliver Gierke 032 * @author Sam Brannen 033 * @since 3.1 034 */ 035public abstract class DatabasePopulatorUtils { 036 037 /** 038 * Execute the given {@link DatabasePopulator} against the given {@link DataSource}. 039 * @param populator the {@code DatabasePopulator} to execute 040 * @param dataSource the {@code DataSource} to execute against 041 * @throws DataAccessException if an error occurs, specifically a {@link ScriptException} 042 */ 043 public static void execute(DatabasePopulator populator, DataSource dataSource) throws DataAccessException { 044 Assert.notNull(populator, "DatabasePopulator must not be null"); 045 Assert.notNull(dataSource, "DataSource must not be null"); 046 try { 047 Connection connection = DataSourceUtils.getConnection(dataSource); 048 try { 049 populator.populate(connection); 050 } 051 finally { 052 DataSourceUtils.releaseConnection(connection, dataSource); 053 } 054 } 055 catch (ScriptException ex) { 056 throw ex; 057 } 058 catch (Throwable ex) { 059 throw new UncategorizedScriptException("Failed to execute database script", ex); 060 } 061 } 062 063}