Spring Hibernate MySQL初始化 [英] Spring Hibernate MySQL initialization

查看:44
本文介绍了Spring Hibernate MySQL初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚Spring Hibernate-MySQL的关系.我的目的是,当我启动程序时,它将在类路径中执行 import.sql 文件.我想做到这一点而又不破坏现有表.我发现了一些有关在启动时执行sql文件的文档.

I'm trying to figure out Spring Hibernate - MySQL relationship. My purpose is, when I start the program, it execute the import.sql file within the classpath. I want to do that without destroy existing tables. I found some documentation about execute sql file on startup.

http://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html

春季官方文件说;

此外,将在启动时执行类路径根目录中名为import.sql的文件.

In addition, a file named import.sql in the root of the classpath will be executed on startup.

但是,Spring销毁了我的表,然后执行了import.sql文件.有没有一种方法可以在不丢失现有数据的情况下执行.sql文件?

But, Spring destroy my tables and than execute import.sql file. Is there a way to execute .sql file without lost existing data?

在下面的问题中,他几乎想要和我一样的东西.

In the below question, he almost wanted the same thing like me.

如何使用Hibernate将初始数据导入数据库?/a>

How to import initial data to database with Hibernate?

但是;

这仅在将hbm2ddl.auto设置为create或create-drop时才有效.

This will also work only if hbm2ddl.auto is set to create or create-drop.

我学习了很多,但是找不到方法.长话短说,如何在不破坏数据库的情况下在启动时运行.sql语句?

I serached a lot but couldn't find a way. Long stroy short, how can I run .sql statement on startup without destroying database?

推荐答案

我终于可以找到自己问题的答案.我在项目中使用了基于Java的配置.互联网上与Spring相关的大多数示例都使用基于xml的配置,因此我很难找到问题的答案.

I can finally find the answers for my own question. I used java-based configuration on my project. Most of the examples on the internet related to spring use xml-based configuration, and it is difficult to me find the answers for my questions.

幸运的是我看到了这个问题;

Luckyly I saw this question;

如何执行SQL插入查询以填充应用程序启动/加载期间的数据库?

答案是

DataSourceInitializer

DataSourceInitializer

它就像一种魅力!

这是在启动时运行SQL语句而不破坏现有数据库的代码段.

Here is the code piece of running SQL statements on startup without destroy existing database.

@Bean
    public DataSourceInitializer dataSourceInitializer() {
    ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
    resourceDatabasePopulator.addScript(new ClassPathResource("/data.sql"));

    DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
    dataSourceInitializer.setDataSource(dataSource());
    dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);
    return dataSourceInitializer;
}

这篇关于Spring Hibernate MySQL初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆