Spring + Hibernate + JPA + multiple databases

泄露秘密 提交于 2019-11-29 08:10:49

This feature is called multi-tenancy.

Hibernate 4 should support it out of the box, though I'm not sure whether it can be integrated with Spring-managed EntityManager.

Alternatively, the easiest way to do it is to intercept creation of database connections, either at ConnectionProvider level or at DataSource level, and choose the appropriate database based on tenant identifier stored in a ThreadLocal variable.

See also:

In spring you can build the EntityManagerFactory dynamically with an Annotation configuration (AnnotationWebConfiguration) using something like this:

@Configuration
public class MyAppConfig{
   public LocalContainerEntityManagerFactoryBean getEmf(){
       LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean ();
       Datasource ds = new .... ; // HERE!! you can create and configure your datasource to point to whatever you need
       emf.setName("system_pu");
       emf.setDatasource(ds);
       emf.setPackagesToScan(""); //optional if no persistence.xml is defined
       return emf;
   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!