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