我正在处理一些旧的应用程序代码,似乎涉及几个概念,因此我希望确保可以将它们改进为一种可靠且严格的实践。
基本上,整个代码都是用这样的 HibernateSessionRequestFilter 包装的
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
sf.getCurrentSession().beginTransaction();
chain.doFilter(request, response);
sf.getCurrentSession().clear();
} catch (...) {
//...
} finally {
sf.getCurrentSession().close();
}
}
然后,有一个拦截器,做这样的事情
private String loadStaff(...) {
//...
try {
dbSession = //...;
dbSession.beginTransaction();
// some logic
dbSession.getTransaction().rollback();
} catch (RuntimeException e) {
//..
}
finally {
if (dbSession != null && dbSession.isOpen()) {
dbSession.clear();
}
}
}
然后还有更多的业务逻辑代码,包括更多的 begintransactions 和 session 清除等。
那么,问题:
- 当 beginTransaction 在同一个 session 中多次调用时会发生什么?
- 有时,调用“clear()”会抛出异常,我认为它是在调用“rollback()”之后发生的。如何解决这个问题?
- 一般来说,将 session.clear() 与事务开始/回滚/提交结合起来的最佳建议实践是什么?
谢谢
最佳答案
您的代码应如下所示,这是处理单个 http 请求事务的方法,
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
// Open the transaction.
sf.getCurrentSession().beginTransaction();
// Handle the request
chain.doFilter(request, response);
// Persist the db changes into database.
sf.getCurrentSession().commit();
} catch (...) {
// Somthing gone wrong while handling the http request so we should remove all the changes and rollback the changes that are done in the current request.
sf.getCurrentSession().rollback()
} finally {
sf.getCurrentSession().close();
}
}
在代码的其他部分不应处理开始事务/关闭/提交事务。它应该只在一个地方处理。
关于java - hibernate 事务开始/回滚/提交与 session.clear(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36409792/