How to connect to multiple databases in Hibernate

后端 未结 6 814
长发绾君心
长发绾君心 2020-11-27 16:37

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. If in t
6条回答
  •  伪装坚强ぢ
    2020-11-27 17:16

    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();
    

    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.

提交回复
热议问题