Spring Data JPA 的 JavaConfig类

之前都是在SpringBoot下使用JPA,可以免配置,在SpringMVC下就需要自己配置了。放这做个备份哈。

一、Maven依赖


  mysql
  mysql-connector-java
  5.1.26



  org.springframework.data
  spring-data-jpa
  1.4.2.RELEASE



  org.hibernate
  hibernate-entitymanager
  4.2.2.Final

二、配置类如下(使用MySQL)

@Configuration
@EnableJpaRepositories("MongoDB")//包名
@EnableTransactionManagement
public class JpaConfig {
    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/test1");//数据库名
        dataSource.setUsername("root");//username
        dataSource.setPassword("admin");//password
        return dataSource;
    }

    @Bean
    public EntityManagerFactory entityManagerFactory() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setDatabase(Database.MYSQL);
        vendorAdapter.setGenerateDdl(true);
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("MongoDB");//包名
        factory.setDataSource(dataSource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory());
        return txManager;
    }
}

你可能感兴趣的:(Spring Data JPA 的 JavaConfig类)