08-05
08
hibernate中使用多数据库
作者:Java伴侣 日期:2008-05-08
public class HibernateSessionFactory {
private static SessionFactory sessionFactory;
public synchronized static Session openSession_db1() throws HibernateException {
if (sessionFactory == null) {
init_db1();
}
return sessionFactory.openSession();
}
public synchronized static Session openSession_db2() throws HibernateException {
if (sessionFactory == null) {
init_db2();
}
return sessionFactory.openSession();
}
private static void init_db1() throws HibernateException {
File file = new File("hibernate1.cfg.xml");
Configuration conf = new Configuration().configure(file);
try {
sessionFactory = conf.buildSessionFactory();
} catch (MappingException e) {
e.printStackTrace();
} catch (HibernateException e) {
e.printStackTrace();
}
}
private static void init_db2() throws HibernateException {
File file = new File("hibernate2.cfg.xml");
Configuration conf = new Configuration().configure(file);
try {
sessionFactory = conf.buildSessionFactory();
} catch (MappingException e) {
e.printStackTrace();
} catch (HibernateException e) {
e.printStackTrace();
}
}
}
================================
而在你的DAO中,获得Session的时候
连接数据库1
Session session1 = HibernateSessionFactory.openSession_db1();
Session session2 = HibernateSessionFactory.openSession_db2();
其他的都一样了。
private static SessionFactory sessionFactory;
public synchronized static Session openSession_db1() throws HibernateException {
if (sessionFactory == null) {
init_db1();
}
return sessionFactory.openSession();
}
public synchronized static Session openSession_db2() throws HibernateException {
if (sessionFactory == null) {
init_db2();
}
return sessionFactory.openSession();
}
private static void init_db1() throws HibernateException {
File file = new File("hibernate1.cfg.xml");
Configuration conf = new Configuration().configure(file);
try {
sessionFactory = conf.buildSessionFactory();
} catch (MappingException e) {
e.printStackTrace();
} catch (HibernateException e) {
e.printStackTrace();
}
}
private static void init_db2() throws HibernateException {
File file = new File("hibernate2.cfg.xml");
Configuration conf = new Configuration().configure(file);
try {
sessionFactory = conf.buildSessionFactory();
} catch (MappingException e) {
e.printStackTrace();
} catch (HibernateException e) {
e.printStackTrace();
}
}
}
================================
而在你的DAO中,获得Session的时候
连接数据库1
Session session1 = HibernateSessionFactory.openSession_db1();
Session session2 = HibernateSessionFactory.openSession_db2();
其他的都一样了。
评论: 0 | 引用: 0 | 查看次数: 667
发表评论