【发布时间】:2014-02-06 16:45:25
【问题描述】:
我已经使用这些技术 + c3p0 构建了一个 Web 服务来处理数据库。它在大多数情况下都可以正常工作,但由于此错误,我有 3-5% 的比例(有时甚至是 10%)的访问失败。
我正在以这种方式使用 Hibernate:
-会话工厂
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
// Create the SessionFactory from hibernate.cfg.xml
return configuration
.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
//reabrimos la sesion si esta cerrada al liberar los recursos
if(sessionFactory.isClosed())
{
System.out.println("Reopen session");
sessionFactory.openSession();
}
return sessionFactory;
}
然后在我的hibernate.cfg.xml 我有以下行:
<property name="current_session_context_class">thread</property>
最后在我的端点中我定义了一个hibernate_session 类,我使用如下:
@Path("/projects")
public class ProjectServiceImpl {
@Context
SecurityContext security;
Session hibernate_session = null;
@POST
@Path("sync.json")
@Produces(value = {"application/json",
"application/vnd.myapp-v1+json",
"application/vnd.myapp-v2+json"})
public Response syncProjects(
@DefaultValue("") @FormParam("projects") String in_projects_str,
@DefaultValue("0") @FormParam("last_sync") long last_sync,
@Context Request request) {
//...
hibernate_session = HibernateUtil.getSessionFactory()
.getCurrentSession();
if (hibernate_session == null) {
ResponseMessage rm = new ResponseMessage();
rm.setCode(Status.INTERNAL_SERVER_ERROR.getStatusCode());
rm.setMessage("Hibernate Session is Null");
rm.setType("ERROR");
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(rm)
.type("application/json").build();
}
try {
hibernate_session.beginTransaction();
//Database work...
hibernate_session.flush();
hibernate_session.getTransaction().commit();
}catch (RuntimeException | IllegalAccessException
| InvocationTargetException e) {
try {
if (hibernate_session.getTransaction() != null) {
hibernate_session.getTransaction().rollback();
}
} catch (RuntimeException rbe) {
System.err.println("Couldn’t roll back transaction");
}
e.printStackTrace();
ResponseMessage rm = new ResponseMessage();
rm.setCode(Status.INTERNAL_SERVER_ERROR.getStatusCode());
rm.setMessage(e.getMessage());
rm.setType("ERROR");
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(rm)
.type("application/json").build();
}
}
return Response.ok().entity(result_entity)
.type("application/json").build();
}
我的hibernate_session 是一个类属性,我必须将其更改为局部变量吗?据我所知,端点将在不同的线程中执行,因此我假设我正在使用端点容器类的不同实例,并且这些类属性不会被多个请求覆盖。
我们将不胜感激您对此主题的任何启发,
提前致谢
【问题讨论】:
-
检查您是否没有在
//Database work...部分的某处开始另一个事务 -
有类级别的注解吗?
-
我添加了类级别注释@stevedbrown
-
也许会有完整的堆栈跟踪,我们可以更好地诊断您的问题。
标签: java web-services hibernate jersey jackson