一尘不染

如何在Spring JPA Web应用程序中设置一些Hibernate属性?

hibernate

我正在尝试摆脱persistence.xmlSpring JPA
Web应用程序中的典型文件。到目前为止,我已经成功注入EntityManager了以下内容:

@Configuration
@EnableTransactionManagement
public class JpaConfig {

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(){

        LocalContainerEntityManagerFactoryBean factoryBean
            = new LocalContainerEntityManagerFactoryBean();

        factoryBean.setDataSource( this.restDataSource() );
        factoryBean.setPackagesToScan( new String[ ] { "com.jverstry" } );
        factoryBean.setPersistenceUnitName("MyMy");

        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(){
         {
            // JPA properties ...
         }
        };

        factoryBean.setJpaVendorAdapter( vendorAdapter );

        return factoryBean;

    }

    @Bean
    public DataSource restDataSource(){

        DriverManagerDataSource dataSource = new DriverManagerDataSource();

        dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
        dataSource.setUrl("jdbc:hsqldb:mem:testdb");
        dataSource.setUsername("sa");
        dataSource.setPassword("");

        return dataSource;

    }

    @Bean
    public PlatformTransactionManager transactionManager(){

        JpaTransactionManager transactionManager = new JpaTransactionManager();

        transactionManager.setEntityManagerFactory(
            this.entityManagerFactoryBean().getObject() );

        return transactionManager;

    }

}

我设法移动了persistence.xml的属性作为数据源:

<properties>
    ... 
    <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
    <property name="hibernate.hbm2ddl.auto" value="create"/>
</properties>

但是如何设置上面剩下的两个hibernate属性?谢谢


阅读 378

收藏
2020-06-20

共1个答案

一尘不染

Spring提供了一种使用AbstractJpaVendorAdaptersetDatabase()setGenerateDdl(),尽管setGenerateDdl()不采用DDL模式)以与提供者无关的方式配置这些选项的方法。

另外,您可以将任意属性传递给LocalContainerEntityManagerFactory使用setJpaProperties()(或setJpaPropertyMap()):

Properties props = new Properties();
props.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
props.put("hibernate.hbm2ddl.auto", "create");
factoryBean.setJpaProperties(props);
2020-06-20