Hi,
I am writing a web application that allows a user to get an employee's personal information and edit it (email, phone, name, etc). When I deploy the application on the server, if I try edit the employee, I can occasionally get an error saying "Hibernate session is already closed." My code for talking to the database via hibernate is below:
/*
* File: EmployeeMapper.java
*/
package org.hibernate.employee;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
* This class represents the data mapper for an employee to the
* database.
*/
public class EmployeeMapper {
/**
* Constructs an EmployeeMapper object.
*/
public EmployeeMapper() {
}
/**
* Finds an employee in the database by the username specified.
*
* @param username the username to find
* @return the employee if the username is in the database, null otherwise
*/
public Employee findByUserName(String username) {
Session session = SessionFactoryUtil.getInstance().getCurrentSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Query q = session.createQuery("from Employee e where e.username='"
+ username + "'");
List results = q.list();
for (Object o : results) {
Employee e = (Employee) o;
return e;
}
} catch (RuntimeException e) {
e.printStackTrace();
} finally {
session.close();
}
return null;
}
/**
* Updates the employee in the database by writing it to the database.
*
* @param employee the employee to update in the database
* @throws Exception
*/
public void updateEmployee(Employee employee) {
Session session = SessionFactoryUtil.getInstance().getCurrentSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.update(employee);
session.getTransaction().commit();
} catch(RuntimeException e){
if(tx != null){
tx.rollback();
}
throw e;
} finally {
session.close();
}
}
}
Does anyone have any suggestions for what I should do? If you need to post other classes or files to get more information on this program, please state what you need.