同一个工程操作两个数据库,hibernate
同一个工程操作两个数据库,我用的是hibernate
请问能行吗,如何操作,帖点代码上来
[解决办法]
你用那个库就选择调用那个库的配置文件,比如misdb.cfg.xml和middb.cfg.xml
import java.util.Hashtable;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
public static final String MISDB_SESSION_FACTORY = "misdb";
public static final String MIDDB_SESSION_FACTORY = "middb";
private static String CONFIG_FILE_LOCATION = "hibernate.cfg.xml";
private static String MISDB_CONFIG_FILE = "misdb.cfg.xml";
private static String MIDDB_CONFIG_FILE = "middb.cfg.xml";
private static Hashtable hashSessionFactories = new Hashtable();
private static Hashtable hashConfigures = new Hashtable();
public static final ThreadLocal threadLocal = new ThreadLocal();
private HibernateUtil() {
super();
}
private static Properties dbProp = new Properties();
static {
dbProp.setProperty(MISDB_SESSION_FACTORY, MISDB_CONFIG_FILE);
dbProp.setProperty(MIDDB_SESSION_FACTORY, MIDDB_CONFIG_FILE);
try {
Configuration cfg2 = new Configuration().configure(MISDB_CONFIG_FILE);
hashSessionFactories.put(MISDB_SESSION_FACTORY, cfg2.buildSessionFactory());
hashConfigures.put(MISDB_SESSION_FACTORY, cfg2);
Configuration cfg3 = new Configuration().configure(MIDDB_CONFIG_FILE);
hashSessionFactories.put(MIDDB_SESSION_FACTORY, cfg3.buildSessionFactory());
hashConfigures.put(MIDDB_SESSION_FACTORY, cfg3);
} catch (Throwable e) {
}
}
/**
* 根据指定的配置文件,获取Hibernate Session。
*
* @param factoryName
* 指定Hibernate Factory的名称。
* @return Hibernate数据库连接。
* @throws HibernateException
*/
public synchronized static Session getSession(String factoryName)
throws HibernateException {
logger.trace("Entering");
SessionFactory sf = (SessionFactory) hashSessionFactories.get(factoryName);
if (sf == null) {
Configuration cfg = new Configuration().configure(dbProp.getProperty(factoryName));
sf = cfg.buildSessionFactory();
hashSessionFactories.put(factoryName, sf);
hashConfigures.put(factoryName, cfg);
}
Hashtable hashSessions = (Hashtable) threadLocal.get();
if (hashSessions == null) {
hashSessions = new Hashtable();
}
Session s = (Session) hashSessions.get(factoryName);
// Open a new Session, if this Thread has none yet
if (s == null ¦ ¦ !s.isOpen()) {
s = sf.openSession();
hashSessions.put(factoryName, s);
threadLocal.set(hashSessions);
}
/* 设置数据库字符集 */
if (factoryName.equals(MISDB_SESSION_FACTORY)
¦ ¦ factoryName.equals(MIDDB_SESSION_FACTORY)) {
PreparedStatement ps;
try {
ps =
s.connection().prepareStatement(
"alter session set nls_language = 'Simplified Chinese'");
ps.execute();
ps.close();
} catch (HibernateException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (SQLException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
logger.trace("Exiting");
return s;
}
要用那个session,就HibernateUtil.getSession(HibernateUtil.MISDB_SESSION_FACTORY)或者
HibernateUtil.getSession(HibernateUtil.MIDDB_SESSION_FACTORY)
[解决办法]
可以用Spring,将不同的数据库连接注入到不同的Dao对象。