Stanislau Listratsenka
Stanislau Listratsenka

Reputation: 680

Get appropriate properties for Entity Manager

I need to create my custom configuration for EntityManager, however I want to set all properties suitable for it from application.properties. Here I set properties hibernate.hbm2ddl.auto and hibernate.dialect explicitly. But I don't know which properties will be passed in application.properties. They can be changed from this file. How to get all appropriate properties from application.properties for EntityManager.

@Bean
public LocalContainerEntityManagerFactoryBean entityManager() {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(dataSource());
    em.setPackagesToScan(new String[] {ENTITY_TO_SCAN});

    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);

    Map<String, Object> properties = new HashMap<>();
    properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
    properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
    em.setJpaPropertyMap(properties);

    return em;
}

Upvotes: 3

Views: 2374

Answers (1)

Shawrup
Shawrup

Reputation: 2734

All your appropriate properties will be available in JpaProperties bean, if they are declared properly in application.properties file.

    @Autowired
    JpaProperties jpaProperties;

The jpa properties format should be like this.

spring.jpa.properties.hibernate.show_sql=false
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect

prefix spring.jpa.properties.*
Then you can update your entity manager bean like

@Bean
public LocalContainerEntityManagerFactoryBean entityManager(JpaProperties jpaProperties) {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(dataSource());
    em.setPackagesToScan(new String[] {ENTITY_TO_SCAN});

    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);
    em.setJpaPropertyMap(jpaProperties.getProperties());

    return em;
}

Upvotes: 1

Related Questions