2016-11-05 154 views
0

我想在我運行此數據源配置時插入sql數據,但無法獲取測試類中的數據。如果我首先在測試類中創建數據並獲取它,它就可以工作。Hsqldb沒有填充數據

@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()); 
} 

裏面一個識別TestClass:

@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)); 

} 

回答

0

Spring就會查找data.sql以及數據 - $ {}平臺.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

+0

現在我得到這個錯誤:「用戶缺少特權或找不到對象:用戶「我試圖用用戶填充後,我猜測在我嘗試運行測試時,內存數據庫不會保留數據 – T3rraform