单测中使用内存式数据库加载自定义的sql脚本

import com.insgeek.platform.rule.RuleApplication;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Profile;
import org.springframework.core.io.ClassPathResource;

import javax.sql.DataSource;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author jiangliangyou
 * @date 2020-07-08
 */
@Slf4j
@Configuration
@Import(value = {RuleApplication.class})
@Profile("test")
public class TestBeanConfig {
	@Bean
	public DataSource getDataSource() throws SQLException {
		DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
		dataSourceBuilder.driverClassName("org.h2.Driver");
		dataSourceBuilder.url("jdbc:h2:mem:test;database_to_upper=false;");
		dataSourceBuilder.username("sa");
		dataSourceBuilder.password("").build();
		DataSource dataSource = dataSourceBuilder.build();
		Connection connection = null;
		try {
			ClassPathResource classPathResource = new ClassPathResource("test.sql");
			connection = dataSource.getConnection();
			ScriptRunner runner = new ScriptRunner(connection);
		    runner.setErrorLogWriter(null);
            runner.setLogWriter(null);
         // 执行SQL脚本
            runner.runScript(new InputStreamReader(classPathResource.getInputStream(), StandardCharsets.UTF_8));
            // 关闭连接
            connection.close();
            // 若成功,打印提示信息
            System.out.println("====== SUCCESS ======");
		} catch (Exception e) {
			log.error(e.getMessage());
		} finally {
			if (connection != null) {
				connection.close();
			}
		}
		return dataSource;
	}
}

  单测中使用内存式数据库加载自定义的sql脚本

 

单测中使用内存式数据库加载自定义的sql脚本

上一篇:mysql-Sql是怎么优化的?


下一篇:postgres 将数据库中的所有所有权限分配给用户