我正在从XML切换到基于Java的Spring配置。以下是我的xml配置,用于设置和初始化我的H2数据库。
<beans profile="test-h2">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:target/h2/pps;AUTO_SERVER=TRUE"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<bean id="entityManagerFactory" parent="entityManagerFactoryCommonParent">
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create-drop</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
</beans>
以下是基于java的配置,用于在服务器模式下设置我的H2数据库。
private static final String H2_JDBC_URL_TEMPLATE = "jdbc:h2:%s/db/merchant;AUTO_SERVER=TRUE";
private DataSource createH2DataSource() {
String jdbcUrl = String.format(H2_JDBC_URL_TEMPLATE, System.getProperty("user.home"));
JdbcDataSource ds = new JdbcDataSource();
ds.setURL(jdbcUrl);
ds.setUser("sa");
ds.setPassword("");
return ds;
}
如何运行脚本来初始化架构并添加一些测试数据?有什么想法吗?
答案 0 :(得分:0)
我找到了办法。
@Value("classpath:seed-data.sql")
private Resource H2_SCHEMA_SCRIPT;
@Value("classpath:test-data.sql")
private Resource H2_DATA_SCRIPT;
@Value("classpath:drop-data.sql")
private Resource H2_CLEANER_SCRIPT;
@Bean
public DataSource dataSource(Environment env) throws Exception {
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
}
@Autowired
@Bean
public DataSourceInitializer dataSourceInitializer(final DataSource dataSource) {
final DataSourceInitializer initializer = new DataSourceInitializer();
initializer.setDataSource(dataSource);
initializer.setDatabasePopulator(databasePopulator());
return initializer;
}
private DatabasePopulator databasePopulator() {
final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
populator.addScript(H2_SCHEMA_SCRIPT);
populator.addScript(H2_DATA_SCRIPT);
return populator;
}