Spring执行sql脚本文件的方法

 更新时间:2019年03月01日 10:21:41   作者:志哥的成长笔记  
这篇文章主要介绍了Spring执行sql脚本文件的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

本篇解决 Spring 执行SQL脚本(文件)的问题。

场景描述可以不看。

场景描述:

我在运行单测的时候,也就是 Spring 工程启动的时候,Spring 会去执行 classpath:schema.sql(后面会解释),我想利用这一点,解决一个问题:

一次运行多个测试文件,每个文件先后独立运行,而上一个文件创建的数据,会对下一个文件运行时造成影响,所以我要在每个文件执行完成之后,重置数据库,不单单是把数据删掉,而 schema.sql 里面有 drop table 和create table。

解决方法:

//Schema 处理器
@Component
public class SchemaHandler {
  private final String SCHEMA_SQL = "classpath:schema.sql";
  @Autowired
  private DataSource datasource;
  @Autowired
  private SpringContextGetter springContextGetter;

  public void execute() throws Exception {
    Resource resource = springContextGetter.getApplicationContext().getResource(SCHEMA_SQL);
    ScriptUtils.executeSqlScript(datasource.getConnection(), resource);
  }
}

// 获取 ApplicationContext
@Component
public class SpringContextGetter implements ApplicationContextAware {

  private ApplicationContext applicationContext;

  public ApplicationContext getApplicationContext() {
    return applicationContext;
  }

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
  }
}

备注:

关于为何 Spring 会去执行 classpath:schema.sql,可以参考源码

org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer#runSchemaScripts

private void runSchemaScripts() {
    List<Resource> scripts = getScripts("spring.datasource.schema",
        this.properties.getSchema(), "schema");
    if (!scripts.isEmpty()) {
      String username = this.properties.getSchemaUsername();
      String password = this.properties.getSchemaPassword();
      runScripts(scripts, username, password);
      try {
        this.applicationContext
            .publishEvent(new DataSourceInitializedEvent(this.dataSource));
        // The listener might not be registered yet, so don't rely on it.
        if (!this.initialized) {
          runDataScripts();
          this.initialized = true;
        }
      }
      catch (IllegalStateException ex) {
        logger.warn("Could not send event to complete DataSource initialization ("
            + ex.getMessage() + ")");
      }
    }
  }

/**
 * 默认拿 classpath*:schema-all.sql 和 classpath*:schema.sql
 */
private List<Resource> getScripts(String propertyName, List<String> resources,
      String fallback) {
    if (resources != null) {
      return getResources(propertyName, resources, true);
    }
    String platform = this.properties.getPlatform();
    List<String> fallbackResources = new ArrayList<String>();
    fallbackResources.add("classpath*:" + fallback + "-" + platform + ".sql");
    fallbackResources.add("classpath*:" + fallback + ".sql");
    return getResources(propertyName, fallbackResources, false);
  }

参考:https://github.com/spring-projects/spring-boot/issues/9048

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Java字符流和字节流对文件操作的区别

    Java字符流和字节流对文件操作的区别

    本篇文章主要介绍了Java的IO流分为字符流(Reader,Writer)和字节流(InputStream,OutputStream),字节流顾名思义字节流就是将文件的内容读取到字节数组,对初学者很有用,有需要的朋友可以了解一下。
    2016-10-10
  • Springboot应用中Mybatis输出SQL日志的3种方法代码示例

    Springboot应用中Mybatis输出SQL日志的3种方法代码示例

    在前台请求数据的时候,sql语句一直都是打印到控制台的,有一个想法就是想让它打印到日志里,该如何做呢?这篇文章主要给大家介绍了关于Springboot应用中Mybatis输出SQL日志的3种方法,需要的朋友可以参考下
    2024-01-01
  • 详解Spring mvc的web.xml配置说明

    详解Spring mvc的web.xml配置说明

    本篇文章主要介绍了Spring mvc的web.xml配置说明,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-02-02
  • springboot themaleaf 第一次进页面不加载css的问题

    springboot themaleaf 第一次进页面不加载css的问题

    这篇文章主要介绍了springboot themaleaf 第一次进页面不加载css的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-10-10
  • Intellij IDEA使用restclient测试的教程图解

    Intellij IDEA使用restclient测试的教程图解

    这篇文章主要介绍了Intellij IDEA使用restclient测试的教程图解,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-01-01
  • 基于spring三方包类注入容器的四种方式小结

    基于spring三方包类注入容器的四种方式小结

    这篇文章主要介绍了基于spring三方包类注入容器的四种方式小结,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09
  • Spring AOP详解面向切面编程思想

    Spring AOP详解面向切面编程思想

    Spring是一个广泛应用的框架,SpringAOP则是Spring提供的一个标准易用的aop框架,依托Spring的IOC容器,提供了极强的AOP扩展增强能力,对项目开发提供了极大地便利
    2022-06-06
  • mybatis 字段名自动转小写的实现

    mybatis 字段名自动转小写的实现

    这篇文章主要介绍了mybatis 字段名自动转小写的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-03-03
  • SpringCloud实现Eureka服务注册与发现

    SpringCloud实现Eureka服务注册与发现

    这篇文章主要介绍了SpringCloud如何实现Eureka服务注册与发现,帮助大家更好的理解和学习使用SpringCloud,感兴趣的朋友可以了解下
    2021-05-05
  • Callable实现多线程步骤详解

    Callable实现多线程步骤详解

    这篇文章主要介绍了Callable实现多线程步骤详解,Callable是一个接口,用于实现多线程,与实现Runnable类似,但是功能更强大,该方法可以在任务结束后提供一个返回值,需要的朋友可以参考下
    2023-10-10

最新评论