我有一個用于 Mysql 的測驗容器,我需要在容器啟動后匯入轉儲檔案。我在下面嘗試了兩個選項。
public class AbstractTest {
public static MySQLContainer<?> mySQLContainer = new MySQLContainer<>("mysql:5.7");
static {
mySQLContainer
.withDatabaseName("myDatabase")
.withCopyFileToContainer(
MountableFile.forClasspathResource("init.sql", 0744),
"init.sql")
.withUsername("root")
.withPassword("root")
.start();
}
@PostConstruct
@SneakyThrows
public void init() {
option 1 // mySQLContainer.execInContainer("mysql -u root -proot myDatabase < init.sql");
option 2 // mySQLContainer.execInContainer("mysql", "-u", "root", "-proot", "myDatabase", "<", "init.sql");
}
////
}
仍然沒有成功 - 看起來 mysql 無法正確決議我的命令,我接下來作為答案得到:
mysql Ver 14.14 Distrib 5.7.35, for Linux (x86_64) using EditLine wrapper
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Usage: mysql [OPTIONS] [database]
-?, --help Display this help and exit.
-I, --help Synonym for -?
--auto-rehash Enable automatic rehashing. One doesn't need to use
'rehash' to get table and field completion, but startup
////.....
如果使用下一個命令
option 2 // mySQLContainer.execInContainer("mysql", "-u", "root", "-proot");
它作業正常,但這不是我想要的
mysql -u root -proot mydatabase < init.sql 如果我只是從 cli 通過 bash 連接到容器,命令就可以正常作業。
所以我的問題 - 如何通過在影像中執行命令來在 JUnit 測驗容器中的 MySQLContainer 中匯入 SQL 轉儲檔案?
更新:我發現決議“<”符號有問題。所以,基本上這在 CLI 中作業正常:
docker exec -i mycontainer mysql -uroot -proot myDatabase < init.sql
但這不適用于 Java:
mySQLContainer.execInContainer("mysql","-uroot","-proot","myDatabase","<","init.sql");
uj5u.com熱心網友回復:
您需要一個適用于MySql的 applications.properties ,例如:
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword
spring.datasource.driver-class-name =com.mysql.jdbc.Driver
#spring.jpa.show-sql: true
然后你可以在你的 /src/test/resources 中添加一個data.sql它將自動運行。
uj5u.com熱心網友回復:
如果你把它放在一個特殊的路徑,MySQL 可以自動加載一個轉儲檔案。
來自MySQL Docker 鏡像的檔案:
當容器第一次啟動時,將使用提供的配置變數創建和初始化具有指定名稱的新資料庫。此外,它將執行在 /docker-entrypoint-initdb.d 中找到的擴展名為 .sh、.sql 和 .sql.gz 的檔案。檔案將按字母順序執行。您可以通過將 SQL 轉儲安裝到該目錄中并提供帶有貢獻資料的自定義影像來輕松填充您的 mysql 服務。默認情況下,SQL 檔案將匯入由 MYSQL_DATABASE 變數指定的資料庫。
因此,最簡單的方法是使用以下內容復制檔案:
.withCopyFileToContainer(MountableFile.forClasspathResource("init.sql"), "/docker-entrypoint-initdb.d/schema.sql")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/374767.html
