Hsqldb没有填充数据

时间:2016-11-05 17:55:56

标签: java spring orm hsqldb in-memory-database

我想在运行此数据源配置时插入sql数据但我无法在测试类中获取数据。如果我首先在测试类中创建数据并获取它,它就可以工作。

@Configuration
@EnableJpaRepositories("se.system.repository")
public class DBConfig{

@Bean(name = "hsqldb")
public DataSource InMemoryDataSource() {

    EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
    EmbeddedDatabase database = builder
            .setType(EmbeddedDatabaseType.HSQL)
            .addScript("classpath:se/system/sql/create-db.sql")
            .setName("database")
            .build();

    return database;
}

@Bean
public JpaTransactionManager transactionManager(EntityManagerFactory factory) {
    return new JpaTransactionManager(factory);
}

@Bean 
public JpaVendorAdapter jpaVendorAdapter() {

    HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
    adapter.setDatabase(Database.HSQL);
    adapter.setShowSql(false);
    adapter.setGenerateDdl(true); 
    return adapter;
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {

    LocalContainerEntityManagerFactoryBean factory = new    LocalContainerEntityManagerFactoryBean();

    factory.setDataSource(InMemoryDataSource());
    factory.setJpaVendorAdapter(jpaVendorAdapter());
    factory.setPackagesToScan("se.system.model");
    return factory;
}

@Bean
public ResourceDatabasePopulator databasePopulator() {
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setSqlScriptEncoding("UTF-8");
    populator.addScript(new ClassPathResource("se/system/sql/insert-data.sql"));
    return populator;
}

@Bean
public InitializingBean populatorExecutor() {
    return () -> DatabasePopulatorUtils.execute(databasePopulator(), InMemoryDataSource());
}

在测试类中:

@BeforeClass
public static void setUp() throws ServiceException {

    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {

        context.scan("se.system");
        context.refresh();

        userService = context.getBean(UserService.class);


        System.out.println(userService.getUserById(1L));  

 }

1 个答案:

答案 0 :(得分:0)

Spring将查找 data.sql 以及要运行的 data - $ {platform} .sql 文件。它使用Spring JDBC来实现这一点。

尝试将您的sql文件重命名为data.sql并相应地调整您的方法:

populator.addScript(new ClassPathResource("se/system/sql/data.sql"));

而不是

populator.addScript(new ClassPathResource("se/system/sql/insert-data.sql"));

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