我最近创建了一个 Web 服务,它使用 Java 中的静态方法从数据库中获取项目列表。
Web 服务运行良好,并将 JSON 返回给调用者。然而,它只能工作一次。如果您尝试刷新或提出新请求,我会收到一个EntityManagerFactory is closed
error.
Web 服务类如下所示:
public class WebService extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//obtain the list of vehicles from the database
List<Vehicle> vehicles = ExecuteVehicle.getVehicleList();
//create the Gson object and generate the Json
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(vehicles, new TypeToken<List<Vehicle>>(){}.getType());
//send the list of vehicles
JsonArray jsonArray = element.getAsJsonArray();
resp.setContentType("application/json");
resp.getWriter().print(jsonArray);
}
}
正如您所看到的,车辆列表正在使用ExecuteVehicle.getVehicleList()
method.
该方法如下所示:
public static List<Vehicle> getVehicleList(){
//open a Session
Session session = HibernateUtilities.getSessionFactory().openSession();
//start a transaction
session.beginTransaction();
//SELECT STATEMENT for the entire list of Vehicles
Query<Vehicle> query = session.getNamedQuery("SelectAllVehicles"); //query name is declared in the mapping file
List<Vehicle> vehicles = query.list();
//commit the changes and end the transaction
session.getTransaction().commit();
//close the Session
session.close();
//close the SessionFactory
HibernateUtilities.getSessionFactory().close();
return vehicles;
}
这是处理 Session 等的 HibernateUtilities 类:
public class HibernateUtilities {
private static SessionFactory sessionFactory;
private static StandardServiceRegistry standardServiceRegistry;
static{
try {
//configure and build the service registry
standardServiceRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
//create the metadata
Metadata metadata = new MetadataSources(standardServiceRegistry).getMetadataBuilder().build();
//build the SessionFactory
sessionFactory = metadata.getSessionFactoryBuilder().build();
} catch (HibernateException e) {
//in case the SessionFactory cannot be built, then the stackTrace is displayed
e.printStackTrace();
}
}
//method that returns the Hibernate session factory
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}
我的问题是 - 我怎样才能避免EntityManagerFactory is closed
错误。此外,我必须一次又一次地实时获取这个列表。这对于 Hibernate 来说可行吗?要以实时方式(例如,每 2 秒左右)从数据库获取项目列表?我知道这取决于项目的数量等,但我从技术角度询问 - 据我了解,打开和关闭会话需要很长时间 - 我可以在同一个会话中一遍又一遍地执行此操作吗如果是这样,怎么办?