使用java配置的persistence.xml

时间:2014-05-27 19:23:52

标签: java spring hibernate jpa spring-data-jpa

为什么需要persistence.xml文件:

@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages="es.japanathome")
public class DataAccessConfig
{

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

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory()
{
    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();

    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(Boolean.TRUE);
    vendorAdapter.setShowSql(Boolean.TRUE);

    factory.setJpaVendorAdapter( vendorAdapter );
    factory.setDataSource( dataSource() );
    factory.setPackagesToScan("es.japanathome.domain");
    factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
    return factory;
}

Spring知道在哪里可以找到我的实体,所以我不明白为什么还需要这个文件。

1 个答案:

答案 0 :(得分:3)

根据您使用的Spring版本,您可能不需要提供persistence.xml。

从Spring 3.1开始,当您使用LocalContainerEntityManagerFactoryBean时需要persistence.xml is no longer explicitly。基本上添加了packagesToScan,允许Spring找到@Entity类。