Hibernate MultiTenancy with spring jpa

2019-03-01 09:41发布

I want to add multiple tenant into my application using separate schema.My application is based on spring jpa and hibernate. I implement MultiTenantConnectionProvider and CurrentTenantIdentifierResolver. And my configuration class is:

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource){

    LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();

    entityManagerFactory.setPackagesToScan("com.**.api.entity");
    HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
entityManagerFactory.setJpaVendorAdapter(hibernateJpaVendorAdapter);
    Properties jpaProperties = new Properties();
    jpaProperties.put("hibernate.globally_quoted_identifiers",true);
    jpaProperties.put("hibernate.dialect",org.hibernate.dialect.MySQL5Dialect.class);
    jpaProperties.put("hibernate.multi_tenant_connection_provider",multiTenantConnectionProvider);
    jpaProperties.put("hibernate.tenant_identifier_resolver",currentTenantIdentifierResolver);
    jpaProperties.put("hibernate.multiTenancy","SCHEMA");
    entityManagerFactory.setJpaProperties(jpaProperties);

    return entityManagerFactory;
}

And I use MapDataSourceLookup to save dataSources.It works.But it's a little problem. I must assign the packagesToScan.I want it to be a basic service.And some application depend on it.It seems that assign the packagesToScan is not a good practice.

Is there any better way to do it?

0条回答
登录 后发表回答