Use Two hibernate.cfg.xml files in a Application - java

how to specify two hibernate configurations for a one application,
i have created two hibernate files and mention them in SessionFactory.util
hibernateMaster.cfg.xml file is working fine..
but when shut down Master database server and try to use application with hibernateMaster.cfg.xml and retrieve data it gives me "null"
but if i restart the Application it is working fine with hibernateMaster.cfg.xml file
here are my hibernate files
hibernateMaster.cfg.xml
<?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>
<!-- Database Connection Settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.232.143:3306/cps</property>
<property name="hibernate.connection.username">gaiz</property>
<property name="hibernate.connection.password">mysql</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping resource="lib/driver/mappings/Patient.hbm.xml"/>
<mapping resource="lib/driver/mappings/Allergy.hbm.xml"/>
<mapping resource="lib/driver/mappings/Hospital.hbm.xml"/>
<mapping resource="lib/driver/mappings/StatStaff.hbm.xml"/>
<mapping resource="lib/driver/mappings/StatWard.hbm.xml"/>
<mapping resource="lib/driver/mappings/User.hbm.xml"/>
<mapping resource="lib/driver/mappings/UserRole.hbm.xml"/>
<mapping resource="lib/driver/mappings/UserLog.hbm.xml"/>
</session-factory>
</hibernate-configuration>
hibernateSlave.cfg.xml
<?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>
<!-- Database Connection Settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.232.144:3306/cps</property>
<property name="hibernate.connection.username">gaiz2</property>
<property name="hibernate.connection.password">mysql</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping resource="lib/driver/mappings/Patient.hbm.xml"/>
<mapping resource="lib/driver/mappings/Allergy.hbm.xml"/>
<mapping resource="lib/driver/mappings/Hospital.hbm.xml"/>
<mapping resource="lib/driver/mappings/StatStaff.hbm.xml"/>
<mapping resource="lib/driver/mappings/StatWard.hbm.xml"/>
<mapping resource="lib/driver/mappings/User.hbm.xml"/>
<mapping resource="lib/driver/mappings/UserRole.hbm.xml"/>
<mapping resource="lib/driver/mappings/UserLog.hbm.xml"/>
</session-factory>
</hibernate-configuration>
SessionFactoryUtil.java
package lib;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import core.resources.statisticalResource;
public class SessionFactoryUtil {
//This class creates a session factory object by looking at the hibernate configuration (hibernate.cfg.xml)
private static SessionFactory sesFactory;
private static ServiceRegistry sesRegistry;
static Configuration cfg;
static{
try{
cfg= new Configuration().configure("lib/hibernateMaster.cfg.xml");
sesRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
sesFactory=cfg.buildSessionFactory(sesRegistry);
try{
Session session = SessionFactoryUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
System.out.println("Connected to Master Database Server");
}
catch(Throwable ex){
cfg= new Configuration().configure("lib/hibernateSlave.cfg.xml");
sesRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
sesFactory=cfg.buildSessionFactory(sesRegistry);
System.out.println("Connected to Slave Database Server");
}
}
catch(Throwable ex){
System.out.println("Master & Slave Database Error.");
System.err.println("Initial SessionFactory Creation Failed"+ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sesFactory;
}
}
i dnt knw whether i have done something wrong on have done something wrong in SessionFactoryUtil.java .

Your problem is that you initialize your factory in a static way.
static{
...
}
That code is executed only once, when you start your application. That way when you shut down your master server hibernate stills asking for it.
You should initialize both configurations and use the main, if exists, or secondary in other case. You can do this in the getSessionFactory() method, that is executed each time the method is call, but not in an static initializer.

Related

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?
it depends on your strategy, what is the trigger to switch database ?

ERROR: No suitable driver found for jdbc:mysql://localhost:3306/test

I am getting no suitable driver exception. Connection is not created.
package org.srtmun.student.dao.impl;
import javax.transaction.Transaction;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.srtmun.student.dao.RegestrationDAO;
import org.srtmun.student.hibernateplugin.HibernatePlug;
import org.srtmun.student.model.Registration;
public class RegistrationDaoImpl implements RegestrationDAO{
public void addStudent(Registration register) {
System.out.println("RegistrationDaoImpl class1");
SessionFactory factory = HibernatePlug.getFactory();
System.out.println("1");
Session session=factory.openSession();
org.hibernate.Transaction tx=session.beginTransaction();
session.save(register);
tx.commit();
session.close();
}
}
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.password">123</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="Registration.hbm.xml" />
</session-factory>
</hibernate-configuration>
This is my code and and iam facing the Same issue.
You need to add this property to the hibernate.cfg.xml
<property
name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
And you need to have mysql-connector-java jar at the class path.
Your transaction code is not correct (you don't use rollback, for an example). Refer this for how to properly work with that.

Exception : buildSessionFactory - in Hibernate App

I'm working on an E-Commerce App using Hibernate Framework. But I'm facing a problem during the execution. The test program throws an Exception :
Exception in thread "main" java.lang.ExceptionInInitializerError
at HibernateUtil.buildSessionFactory(HibernateUtil.java:19)
at HibernateUtil.<clinit>(HibernateUtil.java:9)
at Test.main(Test.java:10)
Caused by: java.lang.NullPointerException
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processFkSecondPassesInOrder(InFlightMetadataCollectorImpl.java:1708)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1617)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:278)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:692)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at HibernateUtil.buildSessionFactory(HibernateUtil.java:14)
... 2 more
My HibernateUtil :
import org.hibernate.*;
import org.hibernate.cfg.*;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- local connection properties -->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/ecom</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.pool_size">10</property>
<!-- dialect for MySQL -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="cache.use_query_cache">false</property>
<mapping class="Metier.Category"/>
<mapping class="Metier.Customer"/>
<mapping class="Metier.CustomerOrder"/>
<mapping class="Metier.orderedProduct"/>
<mapping class="Metier.orderedProductID"/>
<mapping class="Metier.Product"/>
</session-factory>
</hibernate-configuration>
Please tell me what is the source of the Exception.
Cheers.

how to map classes in hibernate using the class attribute?

I have a problem in my maven project
click the links below to see it
I added this to my hibernate.cfg but didn't work
<mapping package="com.redpass.entities"/>
<mapping class="com.redpass.entities.MyReference"/>
console error
Project Explorer
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/avocatbd</property>
<property name="connection.username">root</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- <mapping package="com.redpass.entities"/>
<mapping class="com.redpass.entities.MyReference"/> -->
</session-factory>
</hibernate-configuration>
I should add this:
configuration.configure("hibernate.cfg.xml");
return configuration
.buildSessionFactory(new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build());
to my HibernateUtil Class to tell that we want to configure using the hibernate.cfg.xml file and map the classes like this:
<mapping class="com.redpass.entities.Partie"/>
<mapping class="com.redpass.entities.Societe"/>

Hibernate does not see data inserted from external application

I am using Hibernate as an ORM for a server daemon.
This code returns no items if the table associated is empty at run time but has an item added outside of hibernate.
public static List<QueueItem> queue()
{
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.openSession();
session.flush();
session.clear();
#SuppressWarnings("unchecked")
List<QueueItem> topList = session.createQuery("FROM QueueItem i ORDER BY i.id asc").setMaxResults(3).list();
session.close();
return topList;
}
Here is the hibernate config
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<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://10.10.1.4/lanjukebox_test</property>
<property name="hibernate.connection.username">ussqldev</property>
<property name="hibernate.connection.password">ussqldev</property>
<property name="hibernate.jdbc.batch_size">25</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.cache.use_second_level_cache">false</property>
<property name="show_sql">false</property>
<property name="hbm2ddl.auto">validate</property>
<!-- List of XML mapping files -->
<mapping resource="usagisoft/lan/jukebox/domain/entities/Song.hbm.xml"/>
<mapping resource="usagisoft/lan/jukebox/domain/entities/Id3.hbm.xml"/>
<mapping resource="usagisoft/lan/jukebox/domain/entities/QueueItem.hbm.xml"/>
<mapping resource="usagisoft/lan/jukebox/domain/entities/Vote.hbm.xml"/>
<mapping resource="usagisoft/lan/jukebox/domain/entities/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
If I create an object and persist it from within the application it works fine, If there is already data in the table and I insert the data it finds the other objects, the issue arises as soon as the table is empty during run time.
This is a big issue because another application handles the inserting of data for these objects.
I am using hibernate 4.2.7.Final with Java 1.7(jdk1.7.0_45) in eclipse.
You can resolve this problem since
hibernate.cfg.xml
adding this tag:
<property name="hibernate.connection.autocommit">true</property>

Categories

Resources