我正在編寫一個Web應用程序,允許用戶獲取員工的個人信息並對其進行編輯(電子郵件,電話,姓名等)。當我在服務器上部署應用程序時,如果嘗試編輯員工,偶爾會出現一條錯誤消息,提示「Hibernate會話已關閉」。我通過休眠與數據庫交談的代碼如下:會話中的休眠問題
/*
* 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();
}
}
}
有沒有人對我應該做什麼有什麼建議?如果您需要發佈其他課程或文件以獲取有關此計劃的更多信息,請說明您需要什麼。