|
| 1 | +package com.baeldung.config; |
| 2 | + |
| 3 | +import java.util.Properties; |
| 4 | + |
| 5 | +import javax.sql.DataSource; |
| 6 | + |
| 7 | +import org.springframework.beans.factory.annotation.Autowired; |
| 8 | +import org.springframework.context.annotation.Bean; |
| 9 | +import org.springframework.context.annotation.Configuration; |
| 10 | +import org.springframework.context.annotation.PropertySource; |
| 11 | +import org.springframework.core.env.Environment; |
| 12 | +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; |
| 13 | +import org.springframework.jdbc.datasource.DriverManagerDataSource; |
| 14 | +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; |
| 15 | +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; |
| 16 | + |
| 17 | +//@Configuration |
| 18 | +@EnableJpaRepositories(basePackages = "com.baeldung.repositories") |
| 19 | +// @PropertySource("persistence-h2.properties") |
| 20 | +// @PropertySource("persistence-hsqldb.properties") |
| 21 | +// @PropertySource("persistence-derby.properties") |
| 22 | +public class DbConfig { |
| 23 | + |
| 24 | + @Autowired |
| 25 | + private Environment env; |
| 26 | + |
| 27 | + @Bean |
| 28 | + public DataSource dataSource() { |
| 29 | + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); |
| 30 | + dataSource.setDriverClassName(env.getProperty("driverClassName")); |
| 31 | + dataSource.setUrl(env.getProperty("url")); |
| 32 | + dataSource.setUsername(env.getProperty("user")); |
| 33 | + dataSource.setPassword(env.getProperty("password")); |
| 34 | + return dataSource; |
| 35 | + } |
| 36 | + |
| 37 | + @Bean |
| 38 | + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { |
| 39 | + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); |
| 40 | + em.setDataSource(dataSource()); |
| 41 | + em.setPackagesToScan(new String[] { "com.baeldung.models" }); |
| 42 | + em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); |
| 43 | + em.setJpaProperties(additionalProperties()); |
| 44 | + return em; |
| 45 | + } |
| 46 | + |
| 47 | + final Properties additionalProperties() { |
| 48 | + final Properties hibernateProperties = new Properties(); |
| 49 | + if (env.getProperty("hibernate.hbm2ddl.auto") != null) { |
| 50 | + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); |
| 51 | + } |
| 52 | + if (env.getProperty("hibernate.dialect") != null) { |
| 53 | + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); |
| 54 | + } |
| 55 | + if (env.getProperty("hibernate.show_sql") != null) { |
| 56 | + hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql")); |
| 57 | + } |
| 58 | + return hibernateProperties; |
| 59 | + } |
| 60 | + |
| 61 | +} |
0 commit comments