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

查看:46
本文介绍了如何在 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. 如果在同一个 Web 应用程序中我需要连接到 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?

推荐答案

以注解映射为例:

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天全站免登陆