简体   繁体   中英

Connect to a database dynamically in hibernate

So I have multiple pluggable databases (PDBs) and I want to connect to any one of them dynamically using Hibernate. How do I achieve such functionality?

To connect to PDB1 (and likewise for other PDBs), I have:

protected void setupPdb1() {
    final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
            .configure("hibernate-1.cfg.xml") // configures settings from hibernate.cfg.xml
            .build();
    try {
        sessionFactory1 = new MetadataSources(registry).buildMetadata().buildSessionFactory();
    } catch (Exception ex) {
        StandardServiceRegistryBuilder.destroy(registry);
        throw new RuntimeException(ex);
    }
}

My hibernate config file corresponding to PDB1 is as follows:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>

    <property name="connection.url">jdbc:oracle:thin:@//localhost:1521/pdb1.oradev.oraclecorp.com</property>
    <property name="connection.username">test</property>
    <property name="connection.password">password12</property>
    <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
    <property name="dialect">org.hibernate.dialect.Oracle12cDialect</property>

    <property name="show_sql">true</property>

    <property name="format_sql">true</property>
    <property name="hbm2ddl.auto">create</property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>
    <property name="current_session_context_class">thread</property>

    <mapping class="net.codejava.hibernate.Book" />

  </session-factory>
</hibernate-configuration>

The issue with this approach is there is one config file for each PDB. How do I dynamically select the PDB to connect to using Hibernate?

这取决于您的策略,切换数据库的触发因素是什么?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM