我是 Hibernate 的新手,正在尝试一些东西。 一件似乎很有趣的事情是如何连接到不同的数据库? 我在这里有两个问题:
- 如果我需要在同一个网络应用程序中连接到 MySQL 和 Oracle,我该怎么做?
- 我正在使用 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/36735746/