我的Spring Boot应用程序JPA配置出现问题。我有两个配置文件-dev(H2 db)和prod(PostgreSQL)。我想在没有Spring Boot“ magic”的情况下手动设置JPA,所以我创建了如下所示的配置类
@Configuration
@EnableTransactionManagement
public class PersistenceContext {
@Primary
@Bean
public DataSourceProperties dataSourceProperties() {
return new DataSourceProperties();
}
@Bean
public DataSource dataSource(DataSourceProperties properties) {
return properties
.initializeDataSourceBuilder()
.type(HikariDataSource.class)
.build();
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource(dataSourceProperties()));
em.setPackagesToScan("model");
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
return em;
}
@Bean
public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) {
return new JpaTransactionManager(emf);
}
}
当我想测试保存到开发配置文件中的数据库时,会出现问题。当我执行测试时,出现此错误:
10:37:47.951 [main] DEBUG org.hibernate.SQL - insert into Book (id, author, bookType, bookstore, new_price, old_price, title, url) values (null, ?, ?, ?, ?, ?, ?, ?)
10:37:47.955 [main] DEBUG o.h.e.jdbc.spi.SqlExceptionHelper - could not prepare statement [insert into Book (id, author, bookType, bookstore, new_price, old_price, title, url) values (null, ?, ?, ?, ?, ?, ?, ?)]
org.h2.jdbc.JdbcSQLException: Table "BOOK" not found; SQL statement:
insert into Book (id, author, bookType, bookstore, new_price, old_price, title, url) values (null, ?, ?, ?, ?, ?, ?, ?) [42102-197]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:357)
我的application-dev.properties文件如下
spring.datasource.url=jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.platform=h2
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.generate-ddl=true
spring.data.jpa.repositories.enabled=true
spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.show-sql=true
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
我发现spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop
可能有问题,原因是当我通过PersistenceContext类内的属性映射设置此属性时,它可以正常工作。我不知道如何通过属性文件正确设置它。预先感谢您的帮助。
答案 0 :(得分:0)
spring.jpa.hibernate.ddl-auto=update
和spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop
做同样的事情。但是,由于您选择不使用Spring Autoconfiguration Magic,所以这些属性无效。
因此,您必须使用JPA属性映射并将其设置在LocalContainerEntityManagerFactoryBean
中。