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