Reputation: 3578
How can I connect to more than one mysql database dynamically using Hibernate?
Upvotes: 2
Views: 6639
Reputation:
Create a Class which contains HibernateProperties and SessionFactory entities. Something like:
public class HibernateSessionFactory {
private static final long serialVersionUID = 1L;
private static Log log = LogFactory.getLog(HibernateSessionFactory.class);
private Resource[] mappingLocations;
private Properties hibernateProperties;
private SessionFactory factory;
It'll be nice if you could later use Spring and inject this class with the database connection details, and later assign this HibernateSessionFactory to the related DAO classes.
I did it before, more or less it looks like this:
<bean id="mapHibernateFactory"
class="com.geofencing.dao.hibernate.HibernateSessionFactory"
init-method="init" destroy-method="dispose" scope="singleton">
<property name="mappingResources">
<list>
..... your hibernate mapping files .....
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">false</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.connection.isolation">4</prop>
<prop key="hibernate.connection.autocommit">false</prop>
<prop key="hibernate.connection.url">${jdbc.url}</prop>
<prop key="hibernate.connection.username">${jdbc.username}</prop>
<prop key="hibernate.connection.password">${jdbc.password}</prop>
<prop key="hibernate.connection.driver_class">${jdbc.driverClassName}</prop>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.c3p0.min_size">5</prop>
<prop key="hibernate.c3p0.max_size">20</prop>
<prop key="hibernate.c3p0.timeout">1800</prop>
<prop key="hibernate.c3p0.max_statements">50</prop>
<prop key="hibernate.cache.provider_class"> org.hibernate.cache.EhCacheProvider</prop>
<prop key="net.sf.ehcache.configurationResourceName">WEB-INF/ehcache.xml</prop>
<prop key="hibernate.cglib.use_reflection_optimizer">false</prop>
<prop key="hibernate.connection.zeroDateTimeBehavior">convertToNull</prop>
<prop key="hibernate.connection.autoReconnect">true</prop>
<prop key="hibernate.connection.autoReconnectForPools">true</prop>
</props>
</property>
</bean>
Not sure how to do it with annotation though.
Upvotes: 1
Reputation: 921
If you use hibernate with out spring you can have multiple hibernate properties xml for each database. In those xml files you can specify the database host,username,password ,database name and other connection properties. You can create multiple session Factories using xml files and use the correct session factory in DAO classes.
Upvotes: 3
Reputation: 32969
I believe in Spring you can have multiple SessionFactories each using a separate DataSource. You could pass the specific SessionFactory to the appropriate DAO.
Upvotes: 5