I'm using the opensession() method of session factory because i can't use getCurrentsession(i need to have few open sessions concurrently because I'm using hibernate pagination in my pages). for each transaction i'm opening and closing the session. The problem is that i have some missing data just the time i've inserted them. Actually there is inconsistency between DB and hibernate session. How can i fix this problem?
I have the regular hibernateUtil class. the getSession method is like this:
Code:
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
and here is a method for saving records:
Code:
public static boolean add(Object object, TransUser user) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Session session = null;
Transaction tx = null;
try {
DateUtil dateUtil = DateUtil.getInstance();
Persistent persistent = new Persistent(user.getUserId(), dateUtil.getCurrentDate("/"), dateUtil.getInstance().getCurrentTime(),
null, null, null, null, null, null, null, user.getWorkGroup());
reflector.getSetterMethod(object, "persistent").invoke(object, persistent);
session = HibernateUtil.getSession();
tx = session.beginTransaction();
session.save(object);
tx.commit();
log.error("saved successfully");
return true;
}
catch (HibernateException he) {
tx.rollback();
log.error("Could not save !" + he.getMessage());
throw new IllegalAccessException(he.getMessage());
}
finally {
HibernateUtil.closeSession();
}
}
i also use the following methods when i want to insert or update different entities with the same transaction:
Code:
/**
* @return :Session
*/
public static Session beginTransaction() {
Session session = null;
Transaction tx = null;
session = HibernateUtil.getSession();
tx = session.beginTransaction();
return session;
}
/**
* @param session :Session
* @return :boolean
*/
public static boolean endTransaction(Session session) throws IllegalAccessException {
Transaction tx = session.getTransaction();
try {
tx.commit();
log.error("commited successfully");
return true;
}
catch (HibernateException he) {
tx.rollback();
log.error("Could not commit !" + he.getMessage());
throw new IllegalAccessException(he.getMessage());
}
finally {
HibernateUtil.closeSession();
}
}