Tables not getting created in multiple databases in spring boot application

后端 未结 3 1270
再見小時候
再見小時候 2020-12-29 09:41

I am working on spring boot multi tenancy application. I have configured multi datasources as shown below :

application.properties

spring.multitenanc         


        
相关标签:
3条回答
  • 2020-12-29 10:01

    As @Alex said, you need differnt EntityManagers, TransactionManager and Datasources. Here is how I would do it

    @Configuration
    @EnableJpaRepositories(
        entityManagerFactoryRef = "dataSource1EntityManagerFactory",
        transactionManagerRef = "dataSource1TransactionManager",
        basePackageClasses = dataSource1Repository.class)
    public class DataSource1Config extends SqlConfig{// Put all common code in base class SqlConfig. If not remove it
    
        @Bean
        @Primary
        public DataSource dataSource1() {
            //create dataSource using MultitenancyProperties::getDataSource1
        }
    
        @Primary
        @Bean(name = "dataSource1TransactionManager")
        PlatformTransactionManager dataSource1TransactionManager(EntityManagerFactory dataSource1EntityManagerFactory) {
            JpaTransactionManager txManager = new JpaTransactionManager();
            txManager.setEntityManagerFactory(dataSource1EntityManagerFactory);
            return txManager;
        }
    
        @Primary
        @Bean(name = "dataSource1EntityManagerFactory")
        LocalContainerEntityManagerFactoryBean dataSource1EntityManagerFactory() {
            LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
            em.setDataSource(dataSource1());
            em.setPackagesToScan(dataSource1Repository.class.getPackage().getName(), dataSource1ModelClass.class.getPackage().getName());
            em.setPersistenceUnitName("dataSource1Db");
    
            HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
            vendorAdapter.setGenerateDdl(false);
            em.setJpaVendorAdapter(vendorAdapter);
            return em;
        }
    }
    

    You can create two other classes like this. Remember to use @Primary on only one instace of datasource, transactionmanger and entitymanager(doesn't matter which one). Another word of caution, make sure Repository classes are in different packages for all three databases.

    0 讨论(0)
  • 2020-12-29 10:03

    You need 2 different persistence factories, not one, each should produce different EntityManagers for different datasources. Also each entity mapping should be marked to been used only with one entity manager. See full solution here:

    http://www.baeldung.com/spring-data-jpa-multiple-databases

    0 讨论(0)
  • 2020-12-29 10:21

    Try adding the following properties:

    spring.jpa.generate-ddl=true
    
    0 讨论(0)
提交回复
热议问题