Reputation: 21
I now am refactoring one hard code client application to multi tenant application. Application is very big and any change is expensive. We are working now developing a component for to select Connection Provider and is working well, but the application used before hibernate 3.5 and contain an implementation for HibernateUtil as like are in many pages for beginners. The problem is the use for getCurrentSession throught sessionFactory, because this method returned current session that was opened previously. Now, using withOptions method only is possible use openSession() (always creates a new session), and we haven't been able to figure how get current session with open new one. To make me understand, hibernate util looks like below:
public class HibernateUtil implements ObjectFactory {
private static final SessionFactory sessionFactory;
static{ // build session factory
}
public static void beginTransaction() {
if(!sessionFactory.getCurrentSession().getTransaction().isActive())
{
sessionFactory.getCurrentSession().beginTransaction();
}
else
{
sessionFactory.getCurrentSession().getTransaction();
}
}
.
.
.
public static void endTransaction()
{
if(sessionFactory!=null && sessionFactory.getCurrentSession()!=null)
{
sessionFactory.getCurrentSession().close();
}
else
{
throw new RuntimeException("Error ");
}
}
}
So, Session is initialized and a new Transaction is open, Session is never passed back and endTransaction method, for example, uses getCurrentSession to know what session should to close.
I have readed the little documentation from jboss about multitenancy and he tried implementing CurrentTenantIdentifierResolver, but i cant understand how get session open without to change methods returning the Session object and put it into parameters, because this generates thousands of changes.
I appreciate any help or guide. Thanks in advance.
Upvotes: 1
Views: 1333
Reputation: 596
You can do like this:
public Session getSession(String tenant)
{
Session session=null;
Session session_old=null;
try{
session_old=sessionFactory.getCurrentSession();
log.info(session_old);
}catch(Exception e){
log.info("------------no current session----------");
}finally{
if(session_old==null || !tenant.equals(session_old.getTenantIdentifier())){
log.info("**************************Getting new session for tenant="+tenant);
session=sessionFactory.withOptions().tenantIdentifier(tenant).openSession();
}else{
log.info("**************************session from getCurrentSession");
session=session_old;
}
}
return session;
}
Upvotes: 2