Oracle 多用戶/Schema 架構下,同一套 POJO 映射需在運行時切換目標 Schema (如 `POI_BEIJING` → `POI_SHANGHAI`),實現邏輯庫隔離。
移除 `.hbm.xml` 中的 schema 屬性,改由運行時指定:
<class name="com.csc.poimanager.dao.Poi" table="POI"> <!-- 移除 schema="P_BEIJING" -->
...
</class>
<property name="hibernate.default_schema">POI_BEIJING</property>
public static void rebuildSessionFactoryForChangeSchema(String newSchema) {
try {
Properties props = configuration.getProperties();
props.put("hibernate.default_schema", newSchema);
sessionFactory = configuration.buildSessionFactory(); // 重建工廠
System.out.println("Schema 切換成功:" + newSchema);
} catch (Exception e) {
System.err.println("SessionFactory 重建失敗");
e.printStackTrace();
}
}
HibernateSessionFactory.rebuildSessionFactoryForChangeSchema("POI_SHANGHAI");
PoiDAO dao = new PoiDAO();
Transaction tx = dao.getSession().beginTransaction();
dao.save(new Poi("JSfjksdf"));
tx.commit(); // 實際寫入 POI_SHANGHAI.POI 表
SessionFactory 重建影響所有使用者/執行緒,非線程安全,高併發下極危險。SessionFactory 實例,ThreadLocal 綁定當前租戶 Schema。SCHEMA / DATABASE / DISCRIMINATOR 三種策略,配合 CurrentTenantIdentifierResolver 實現零侵入切換。