How to handle several DB schemas with Hibernate?

前端 未结 2 1299
礼貌的吻别
礼貌的吻别 2020-12-18 13:41

In one of my projects, I have an application that manages several clients (or customer if you prefer). For each of them, I have a dedicated schema on a database. However, th

2条回答
  •  情歌与酒
    2020-12-18 14:15

    If only one at a time will every be required, it makes it much simpler. Simply create a SessionFactory per database. Avoid the HibernateUtils static SessionFactory instance approach and you won't have any problems.

    A neat way to do this with Spring if you don't have too many databases (hundreds) is to instantiate a separate Spring ApplicationContext for each one that contains the SessionFactoryBean and DataSource configurations specially for that database.

    You can use Spring mechanisms like PropertyOverrideConfigurer and a common parent ApplicationContext to factor out all the common stuff so that your many child ApplicationContexts are small and maintainable.

    Then when a request comes in, just select the ApplicationContext you want to work with and start pulling beans out of it.

    If you want to do it without Spring, you could also create multiple SessionFactory instances and store the "current" one in a static ThreadLocal.

提交回复
热议问题