我使用Spring Data JPA并使用多个数据库,因此我必须自己配置它而不是使用@HibernateJpaAutoConfiguration
。
public class TesterDbConfig {
@Autowired(required = false)
private PersistenceUnitManager persistenceUnitManager;
@Bean
public JpaProperties testerJpaProperties() {
JpaProperties jpaProperties = new JpaProperties();
return jpaProperties;
}
@Bean
@Primary
@ConfigurationProperties(prefix = "datasource.primary")
public DataSource testerDataSource() {
return (DataSource) DataSourceBuilder.create().type(DataSource.class).build();
}
@Bean
public LocalContainerEntityManagerFactoryBean testerEntityManager(
JpaProperties testerJpaProperties) {
EntityManagerFactoryBuilder builder = createEntityManagerFactoryBuilder(testerJpaProperties);
return builder.dataSource(testerDataSource()).packages(Cabang.class).persistenceUnit("primary")
.build();
}
@Bean
public JpaTransactionManager testerTransactionManager(EntityManagerFactory testerEntityManager) {
return new JpaTransactionManager(testerEntityManager);
}
private EntityManagerFactoryBuilder createEntityManagerFactoryBuilder(
JpaProperties testerJpaProperties) {
JpaVendorAdapter jpaVendorAdapter = createJpaVendorAdapter(testerJpaProperties);
return new EntityManagerFactoryBuilder(jpaVendorAdapter, testerJpaProperties,
this.persistenceUnitManager);
}
private JpaVendorAdapter createJpaVendorAdapter(JpaProperties testerJpaProperties) {
AbstractJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setShowSql(testerJpaProperties.isShowSql());
adapter.setDatabase(testerJpaProperties.getDatabase());
adapter.setDatabasePlatform(testerJpaProperties.getDatabasePlatform());
adapter.setGenerateDdl(testerJpaProperties.isGenerateDdl());
return adapter;
}
}
有了这个,每次我创建一个模型时,我必须在每个变量中使用@Column
,因为在我的数据库中,我使用的是蛇案例,但在模型类中,我使用驼峰案例。
如何设置Hibernate命名策略?
答案 0 :(得分:1)
您可以通过您已在配置中使用的JpaProperties
进行设置:
@Bean
public JpaProperties testerJpaProperties() {
JpaProperties jpaProperties = new JpaProperties();
JpaProperties.Hibernate hibernate = new JpaProperties.Hibernate();
hibernate.setNamingStrategy(SpringNamingStrategy.class);
jpaProperties.setHibernate(hibernate);
return jpaProperties;
}
并添加
@Bean
public LocalContainerEntityManagerFactoryBean testerEntityManager(
JpaProperties testerJpaProperties) {
EntityManagerFactoryBuilder builder = createEntityManagerFactoryBuilder(testerJpaProperties);
return builder.dataSource(testerDataSource())
.packages(Cabang.class)
.persistenceUnit("primary")
.properties(Collections.singletonMap("hibernate.ejb.naming_strategy",testerJpaProperties.getHibernate().getNamingStrategy()))
.build();
}