hibernate - 如何在 Hibernate 中连接到多个数据库

标签 hibernate database

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

  1. 如果我需要在同一个网络应用程序中连接到 MySQL 和 Oracle,我该怎么做?
  2. 我正在使用 MySQL 并有两个数据库 test1 和 test2,如何连接和检索数据?

我在博客中读到我们可以创建不同的配置文件并执行此操作。 我试过了,但没有成功。 这是我尝试过的:

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

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

最佳答案

以注解映射为例:

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 获取每个数据库的 session 。对于映射文件,您只需使用 cfg.addClass 而不是 addAnnotatedClass。在这种情况下,将 cfg.xml 文件放在根包中。这些将具有 Oracle 或 MySQL 方言和连接信息。

关于hibernate - 如何在 Hibernate 中连接到多个数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1921865/

相关文章:

java - 提供值列表作为 Hibernate 搜索中的搜索条件

android - 如何使用 Uri 对象打开现有的 SQLite 数据库?

.net - 更改连接字符串 .NET Oracle 错误

java - 在javafx中的sql server 2014中插入一行数据

mysql - 为 MySql 中的 View 生成唯一长 ID

java - 尝试检索 OracleConnection 但收到 null

java - Hibernate OneToMany 双向不识别外键

java - JPA 继承

mysql - 查询执行成功但在表中插入了其他数据

java - 接口(interface)和数据库