Java 如何通过重用 cfg.xml 和 util 类连接多个数据库?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20819869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to connect multiple database with reusing cfg.xml and util class?
提问by user2848031
I want to connect multiple databases like SQL and Oracle with different databases.So i already had MSSQL hibernate.cfg.xml and Hibernateutil class for session factory.Now i'm trying to connect oracle with different table.
我想将多个数据库(如 SQL 和 Oracle)与不同的数据库连接。所以我已经有 MSSQL hibernate.cfg.xml 和 Hibernateutil 类用于会话工厂。现在我正在尝试将 oracle 与不同的表连接。
Please advise can i use same cgf.xml and util class can configure oracle databases as well.
请告知我是否可以使用相同的 cgf.xml 和 util 类也可以配置 oracle 数据库。
Here is util class.
这是 util 类。
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
@SuppressWarnings("deprecation")
private static SessionFactory buildSessionFactory()
{
try
{
SessionFactory sessionFactory = new Configuration().configure("/DAO/hibernate.cfg.xml").buildSessionFactory();
return sessionFactory;
}
catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
采纳答案by Diversity
You need to provide a cfg.xml for each database.
您需要为每个数据库提供一个 cfg.xml。
Oracle.cfg.xml
mssql.cfg.xml
There you provide the appropriate database connecton configuration, the dialect to use and which hbm
-mapping files for the entity classes are needed
在那里您提供适当的数据库连接配置、要使用的方言以及hbm
需要实体类的哪些映射文件
Within your code you create a single SessionFactory for each database.
在您的代码中,您为每个数据库创建一个 SessionFactory。
SessionFactory oracleSF = Configuration.configure("oracle.cfg.xml").buildSessionFfactory();
SessionFactory msSF = Conf..configure("mssql.cfg.xml").build....
To reuse your util class you just have to pass the name of the config file to the method which creates the SessionFactory as an additional parameter.
要重用您的 util 类,您只需将配置文件的名称传递给创建 SessionFactory 作为附加参数的方法。
The entity classes of the different tables are declared within the appropriate config file and therefore assigned to the right database, so hibernate knows which database to use.
不同表的实体类在适当的配置文件中声明,因此分配给正确的数据库,因此 hibernate 知道要使用哪个数据库。
Also take a look at this discussion which is about multiple schemas with a single cfg:
另请查看此讨论,该讨论是关于具有单个 cfg 的多个模式:
how to use Hibernate for two different schemas in a single database
Have a look here: It is a pretty nice site with an vast amount of tutorials for hibernate:
看看这里:这是一个非常不错的网站,有大量的休眠教程: