javaspringhibernatejpaconfiguration

How to set some Hibernate properties in Spring JPA Web Application?


I am trying to get rid of the typical persistence.xml file in Spring JPA web application. So far, I have managed to inject the EntityManager successfully with the following:

@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;

    }

}

I have managed to move the properties of my persistence.xml for the datasource:

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

but how to I set the two remaining hibernate properties above? Thanks


Solution

  • Spring provides a way to configure these options in provider-independent way using AbstractJpaVendorAdapter (setDatabase() and setGenerateDdl(), though setGenerateDdl() doesn't take DDL mode).

    Alternatively, you can pass arbitrary properties to LocalContainerEntityManagerFactory using setJpaProperties() (or setJpaPropertyMap()):

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