我有一个使用数据库的春季启动项目(domain,jdbcTemplate,mysql)
但是另一个项目的成员无法连接我的mysql数据库。
所以我想在我们开发时为其他成员提供嵌入式h2数据库提供弹簧启动
但我遇到的问题很少是mysql的sql和h2 sql不同。我们必须使用csv data import sql。
mysql:LOAD DATA ...... h2:INSERT INTO表SELECT * FROM CSVREAD(csvfile)
如果我们为mysql和h2制作每个方法,我们必须在部署时更改代码。
这是解决这个问题的任何解决方案吗?
谢谢:)
答案 0 :(得分:0)
将数据库特定数据加载到实现接口的单独组件中,并使用配置文件激活组件。所以当地开发时说你将使用" local"轮廓。像这样:
public interface SpecialDataLoader {
void loadData();
}
@Component
// no @Profile annotation, will be used by default
public class MySqlDataLoader implements SpecialDataLoader {
@Override public void loadData() {
// .. do it LOAD DATA way
}
}
@Component
@Profile("local") // component will be used when "local" profile is active
public class H2DataLoader implements SpecialDataLoader {
@Override public void loadData() {
// .. do it INSERT INTO table SELECT * FROM CSVREAD(csvfile) way
}
}
@Component
public ClassThatUsesTheLoader {
@Autowired SpecialDataLoader specialDataLoader; // the right component will be autowired depending on the profile here
void useSpecialDataLoader() {
specialDataLoader.loadData();
}
}
现在,在本地开发时,您可以使用命令行参数--spring.profiles.active=local
运行应用程序,并使用H2DataLoader
。在生产中,根本不需要指定配置文件,并且将使用MySqlDataLoader
。
请阅读配置文件中的relevant documentation以及如何使用它们。