如何连接到Hibernate中的多个数据库 [英] How to connect to multiple databases in Hibernate

查看:342
本文介绍了如何连接到Hibernate中的多个数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Hibernate的新蜜蜂,尝试的东西。
似乎有趣的一件事是如何连接到不同的数据库?
这里有两个问题:

I am new bee to Hibernate and trying out things. One thing that seems to amuse all is how to connect to different databases? I have two questions here:


  1. 如果在同一个网络应用程序中,我需要连接到MySQL和Oracle,做吗?

  2. 我使用MySQL并拥有两个数据库test1和test2,如何连接和检索数据?

我已经在博客中阅读,我们可以创建不同的配置文件,并做它。
我试了,但不成功。
这是我试过的:

I have read in a blog that we can create different configuration files and do it. I tried it but was not sucessful. Here's what I tried:

SessionFactory sf = (SessionFactory) new Configuration().configure(path);

其中path是配置文件的路径。
这是正确的方法吗?

Where path is the path of the config file. Is this the right way?

推荐答案

使用注释映射作为示例:

Using annotation mappings as an example:

Configuration cfg1 = new AnnotationConfiguration();
cfg1.configure("/hibernate-oracle.cfg.xml");
cfg1.addAnnotatedClass(SomeClass.class); // mapped classes
cfg1.addAnnotatedClass(SomeOtherClass.class);
SessionFactory sf1 = cfg1.buildSessionFactory();

Configuration cfg2 = new AnnotationConfiguration();
cfg2.configure("/hibernate-mysql.cfg.xml");
cfg2.addAnnotatedClass(SomeClass.class); // could be the same or different than above
cfg2.addAnnotatedClass(SomeOtherClass.class);
SessionFactory sf2 = cfg2.buildSessionFactory();

然后使用sf1和sf2获取每个数据库的会话。对于映射文件,您只需使用cfg.addClass而不是addAnnotatedClass。在这种情况下,将cfg.xml文件放在根包中。那些将有Oracle或MySQL方言和连接信息。

Then use sf1 and sf2 to get the sessions for each database. For mapping files, you just use cfg.addClass instead of addAnnotatedClass. Put the cfg.xml files in the root package in this case. Those will have the Oracle or MySQL dialect and connection information.

这篇关于如何连接到Hibernate中的多个数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆