How to access Spring Data configured entity manager (factory) in custom implementation

后端 未结 3 867
伪装坚强ぢ
伪装坚强ぢ 2020-12-23 22:57

I\'m writing a custom implementation for a Spring Data JPA repository. So I have:

  • MyEntityRepositoryCustom => interface with the custom methods
3条回答
  •  有刺的猬
    2020-12-23 23:49

    Spring Data JPA uses Auto configuration classes to auto generate entityManagerFactory, dataSource and transactionManager.

    If you want get access to entityManager and control the instantiation and settings, you need to define your own PersistenceConfiguration. Below is the sample code using Java Config

        @Configuration
        @EnableTransactionManagement
        @EnableJpaRepositories(basePackages = { "com.test.repositories.*" })
        public class PersistenceJpaConfig {
    
            @Autowired
            JpaVendorAdapter jpaVendorAdapter;
    
            @Bean
            public DataSource dataSource() {
                return new EmbeddedDatabaseBuilder()
                        .setName("testdb")
                        .setType(EmbeddedDatabaseType.HSQL)
                        .build();
            }
    
            @Bean
            public EntityManager entityManager() {
                return entityManagerFactory().createEntityManager();
            }
    
            @Bean
            public EntityManagerFactory entityManagerFactory() {
                LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
                lef.setDataSource(dataSource());
                lef.setJpaVendorAdapter(jpaVendorAdapter);
                lef.setPackagesToScan("com.test.domain.*");
                lef.afterPropertiesSet();
                return lef.getObject();
            }
    
            @Bean
            public PlatformTransactionManager transactionManager() {
                return new JpaTransactionManager(entityManagerFactory());
            }
        }
    

    If you have multiple data sources, follow this article.

提交回复
热议问题