温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在Spring中执行sql脚本文件

发布时间:2021-05-18 18:04:00 来源:亿速云 阅读:352 作者:Leah 栏目:编程语言

这篇文章将为大家详细讲解有关如何在Spring中执行sql脚本文件,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

解决方法:

//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);
  }

关于如何在Spring中执行sql脚本文件就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI