【发布时间】:2018-11-25 05:16:26
【问题描述】:
我有一个 REST API,当我几乎同时进行 POST 和 GET 时,我得到了这个异常:
SEVERE: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
java.lang.IllegalStateException: Transaction already active
at org.hibernate.engine.transaction.internal.TransactionImpl.begin(TransactionImpl.java:52)
at org.hibernate.internal.AbstractSharedSessionContract.beginTransaction(AbstractSharedSessionContract.java:409)
at sun.reflect.GeneratedMethodAccessor89.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:355)
at com.sun.proxy.$Proxy58.beginTransaction(Unknown Source)
at utils.HibernateSession.createTransaction(HibernateSession.java:15)
at api.ConversationsREST.getMessages(ConversationsREST.java:128)
它们位于不同的类中,因此没有隐含的全局属性。
失败的线路是这一行:
HibernateSession hs = new HibernateSession();
hs.createTransaction(); // Crash
Wich 指的是我的类 HibernateSession:
public class HibernateSession {
public Session session;
public void createTransaction() {
session = HibernateUtil.getSessionFactory().getCurrentSession(); //THIS WAS WRONG
//EDIT:session = HibernateUtil.getSessionFactory().openSession(); //THIS IS RIGHT
session.beginTransaction();
}
public void commitclose() {
session.getTransaction().commit();
session.close();
}
public void rollbackclose() {
try {
session.getTransaction().rollback();
session.close();
} catch (Exception hibernateexception) {
hibernateexception.printStackTrace();
}
}
}
异常居然在线session.beginTransaction()
我总是做一个 hs.commitclose() 并且在 catch() 块和 404 中我总是做一个 rollbackclose();
问题是当我发出这样的 POST 消息时:
HibernateSession hs = new HibernateSession();
hs.createTransaction();
hs.session.save(whatever);
hs.commitclose();
返回 200 并没关系,但随后 GET 可能会崩溃,但上述异常除外。 当我创建一个新的 HibernateSession 实例时,为什么 Hibernate 似乎试图共享该事务?
这只发生在我在很短的时间内进行两个查询时(我猜想在另一个人的开始和提交之间开始一个事务)。所以我猜 Hibernate 认为会话属性是静态的或类似的东西......
提前感谢您的帮助!
编辑:应要求,HibernateUtil.java(问题一定不在这里,但可能有助于理解):
package utils;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
sessionFactory = build();
}
return sessionFactory;
}
private static SessionFactory build() {
try {
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed: " + ex);
throw new ExceptionInInitializerError(ex);
}
}
}
【问题讨论】:
-
你也可以添加 HibernateUtil...
-
@Ashish451 当然
-
我已经添加了解决方案..你可以试试
标签: java hibernate rest jersey