1

i develop a J2EE application with Hibernate, and i want to have 2 database, the first will be local (in client computer ), and the second will be in the server.
indeed , i want to configure hibernate to connect in the local databases when the global is not accessible. My actual config file :
<hibernate-configuration > <session-factory> <property name= "hibernate.dialect"> org.hibernate.dialect.MySQLDialect</property> <property name= "hibernate.connection.driver_class"> com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost/serverBdd </property> <property name="hibernate.connection.username">root</property> <property name="hibernate.hbm2ddl.auto">update</property> <property name="show_sql">true</property> <property name="hibernate.connection.password"></property> <mapping resource="hibernateConfiguration/Usine.hbm.xml"/> <mapping resource="hibernateConfiguration/Produit.hbm.xml"/> <mapping resource="hibernateConfiguration/Machine.hbm.xml"/> <mapping resource="hibernateConfiguration/Operation.hbm.xml"/> <mapping resource="hibernateConfiguration/Utilisateur.hbm.xml"/> </session-factory> </hibernate-configuration>

how Can i do this ? and if i can't what should i do to solve my problem ?
thanks

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
Achraf Elkari
  • 23
  • 1
  • 8
  • Create two .cfg file and create two different sessionFactory object for client computer and another one for server. – Janny Jul 21 '15 at 15:40
  • Hi thanks for the help, but i must have one config file , and my application will read it automatically, i do : factory = new Configuration().configure().buildSessionFactory(); // to create a factory, so i did not specify the location of .cfg file :/ – Achraf Elkari Jul 21 '15 at 15:47

1 Answers1

0

Sure, here you can find an example that writes in 2 databases at same time, but with a simple if condition you can decide which to use:

First, create 2 hibernate.cfg.xml files as usual but with different names

  • serverconfig.cfg.xml
  • localconfig.cfg.xml

After, in your DAO or wherever you get your hibernate Session simply check if server database and if it is not available use local configuration:

SessionFactory sessionFactory = new Configuration().configure("serverconfig.cfg.xml").buildSessionFactory();

if (sessionFactory == null)
    sessionFactory = new Configuration().configure("localconfig.cfg.xml").buildSessionFactory();

Also, if you use Hibernate 4 or later check this answer

Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109