Saturday, December 17, 2016

Creating EntityManagerFactory in Spring

To create JPA based EntityManagerFactory backed by Hibernate implementation in Spring which gets auto configured, follow the code

@Configuration
@EnableAutoConfiguration
//package containing the mapped model
@EnableJpaRepositories(basePackages = "com.lalit.example.Model")
@EnableTransactionManagement
public class DatabaseConfiguration {
        //You can autowire env which contains values from properties file or you
        //can inject properties directly using $
@Autowired
Environment env;

        //This will also create a pool of connections
@Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("db.driver"));
dataSource.setUrl(env.getProperty("db.url"));
dataSource.setUsername(env.getProperty("db.username"));
dataSource.setPassword(env.getProperty("db.password"));
dataSource.setPoolPreparedStatements(true);
dataSource.setMaxOpenPreparedStatements(20);
return dataSource;

}

@Bean(name="entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
// Put all the Hibernate properties
Properties additionalProperties = new Properties();
additionalProperties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
additionalProperties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
additionalProperties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));

LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setDataSource(dataSource());

JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); entityManagerFactory.setJpaVendorAdapter(vendorAdapter);
entityManagerFactory.setJpaProperties(additionalProperties);

entityManagerFactory.setJpaProperties(additionalProperties);

return entityManagerFactory;
}

        //Hook the transaction manager
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}

        //Hook the exception translator
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}


}

1 comment:

  1. ThanQ so much sir for your beautiful code........... :)

    ReplyDelete