schema.sql中的脚本被执行但是data.sql中的脚本没有执行, 不知道我错过了什么?
我使用Spring Boot和两个数据源我的数据库配置如下
@PropertySource({ "classpath:application.properties" })
@Configuration
@EnableJpaRepositories(
basePackages = "com.projectx.mysql",
entityManagerFactoryRef = "userEntityManager",
transactionManagerRef = "userTransactionManager"
)
public class DataBaseConfig {
@Autowired
Environment env;
@Bean
@Primary
public LocalContainerEntityManagerFactoryBean userEntityManager() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(primaryDataSource());
em.setPackagesToScan(new String[] { "com.projectx.mysql" });
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties = new HashMap<String, Object>();
properties.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto_mysql"));
properties.put("hibernate.dialect", env.getProperty("spring.jpa.properties.hibernate.dialect_mysql"));
properties.put("hibernate.show_sql", env.getProperty("spring.jpa.show-sql"));
em.setJpaPropertyMap(properties);
return em;
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Primary
@Bean
public PlatformTransactionManager userTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(userEntityManager().getObject());
return transactionManager;
}
}
和.properties文件配置如下
spring.datasource.initialize=true
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.show-sql: true
spring.jpa.hibernate.ddl-auto_mysql=update
spring.jpa.properties.hibernate.dialect_mysql=org.hibernate.dialect.MySQL5Dialect
答案 0 :(得分:2)
对于那些在 SpringBoot 2.1+ 世界中偶然发现这个问题的人。
首先,我认为是重要类的完整类名(“publishEvent”的对象...“org.springframework.boot.autoconfigure.jdbc.DataSourceInitializedEvent”
对于未来的读者来说,这个类似乎在这两个版本之间消失了:
以下确实存在:
以下不再存在:
这是我如何“编码”种子数据(“data.sql”)......当我有一个 Java-Config 重类时。
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
@Bean
public DataSource getDataSource() {
//not shown
}
@Bean
public DataSourceInitializer dataSourceInitializer(DataSource ds) {
ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
resourceDatabasePopulator.addScript(new ClassPathResource("/data.sql"));
DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
dataSourceInitializer.setDataSource(ds);
dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);
return dataSourceInitializer;
}
调试提示。您可能希望使用不是魔术文件名的文件名(“data.sql”是魔术名称)来故意避免 spring boot 魔术。特别是从 Spring Boot 2.5 开始。
答案 1 :(得分:1)
当我们看到org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer类的内容通过* .sql文件处理数据库初始化时,问题出在数据源初始化。它有post构造方法如下
@PostConstruct
public void init() {
if (!this.properties.isInitialize()) {
logger.debug("Initialization disabled (not running DDL scripts)");
return;
}
if (this.applicationContext.getBeanNamesForType(DataSource.class, false,
false).length > 0) {
this.dataSource = this.applicationContext.getBean(DataSource.class);
}
if (this.dataSource == null) {
logger.debug("No DataSource found so not initializing");
return;
}
runSchemaScripts();
}
runSchemaScripts()方法将在hibernate模式创建和更新操作完成之前初始化数据,因此如果没有生成数据库模式,那么如果您在SQL脚本中提供了这些方法,那么这些方法将创建模式,但我想在之后执行操作创建/更新了schema,该类包含
@Override
public void onApplicationEvent(DataSourceInitializedEvent event) {
if (!this.properties.isInitialize()) {
logger.debug("Initialization disabled (not running data scripts)");
return;
}
// NOTE the event can happen more than once and
// the event datasource is not used here
if (!this.initialized) {
runDataScripts();
this.initialized = true;
}
}
如果我们使用spring boot默认Datasource
创建机制,则在hibernate架构创建/更新操作之后调用此方法。
但是当我自己创建Datasource
时,它没有创建DataSourceInitializedEvent
,因此未执行数据启动脚本data.sql
。
所以我已经更改了我的数据源创建逻辑以创建DataSourceInitializedEvent
,如下所示,这解决了我的问题。
@Autowired
private ConfigurableApplicationContext applicationContext;
@Bean
@Primary
public LocalContainerEntityManagerFactoryBean userEntityManager() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(primaryDataSource());
em.setPackagesToScan(new String[] { "com.projectx.mysql" });
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties = new HashMap<String, Object>();
properties.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto_mysql"));
properties.put("hibernate.dialect", env.getProperty("spring.jpa.properties.hibernate.dialect_mysql"));
properties.put("hibernate.show_sql", env.getProperty("spring.jpa.show-sql"));
em.setJpaPropertyMap(properties);
this.applicationContext.publishEvent(new DataSourceInitializedEvent(primaryDataSource()));
return em;
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
添加this.applicationContext.publishEvent(new DataSourceInitializedEvent(primaryDataSource()));
以创建DataSourceInitializedEvent
事件
答案 2 :(得分:0)
我设法实例化了2个数据源,并使用this test project在其中一个数据源中启动了模式和数据。希望有所帮助,也许我错过了你的一些要求,使我的建议无效:(
对于ref(猜测你已经看到了这个):https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-two-datasources