-----------------------------TenantMasterFactory.java---------------------------
package com.nen.cn.util;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
@SuppressWarnings("static-access")
public class TenantMasterFactory{
private static Map<String, SessionFactory> sessionmapdfactory = new HashMap<String, SessionFactory>();
private static Map<String, Session> sessionmap = new HashMap<String, Session>();
private static Configuration cfg = null;
private static Properties pps = null;
TenantMasterFactory() {
}
/**
* new sessionFactorys for the Tenants
*/
static {
pps = new Getproperties().getProperties("src/TenantManagerFile.properties");
try {
for (Iterator iter = pps.keySet().iterator(); iter.hasNext();) {
String element = (String) iter.next();
SessionFactory sessionFactory = Configuartion(pps.getProperty(String.valueOf(element)).trim());
sessionmapdfactory.put(String.valueOf(element), sessionFactory);
}
}catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private static SessionFactory Configuartion(String catalog){
cfg = new Configuration();
cfg.configure("/"+ catalog +"hibernate.cfg.xml");
return cfg.buildSessionFactory();
}
public Session getSession(String catalog) {
Session session = sessionmap.get(catalog);
if( session == null || !session.isOpen()){
if(sessionmapdfactory.get(catalog) == null || sessionmapdfactory.get(catalog).isClosed()){
SessionFactory sessionFactory = Configuartion(catalog);
sessionmapdfactory.put(catalog, sessionFactory);
}
session = sessionmapdfactory.get(catalog).openSession();
sessionmap.put(catalog, session);
}
System.out.println(sessionmapdfactory.get(catalog));
return session;
}
}
------------------------------Getproperties .java------------------------
package com.nen.cn.util;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
public class Getproperties {
private static Properties pps = null;
public static Properties getProperties(String fileName) {
pps = new Properties();
try {
FileInputStream ss = new FileInputStream(fileName);
if(ss != null){
pps.load((InputStream) ss);
}
ss.close();
} catch (Exception e) {
System.out.println("The file loader error....");
}
return pps;
}
}
---------------------------TenantManagerFile.properties)---------------------------
1=WIS1
2=WIS2
3=WIS3
4=WIS4
5=WIS5
6=WIS6
7=WIS7
8=WIS8
9=WIS9
10=WIS10
--------------------------------------------------------------------------------------------------
Session session = dao.getSession(catalog);
catalog = TenantManagerFile.properties 前置項
TenantManagerFile.properties 後置項 = 資料庫database名