如何在Struts2 + Hibernate Web App中跨多个dao方法使用同一会话对象? [英] How to use same session object across multiple dao methods in struts2+hibernate web-app?

查看:63
本文介绍了如何在Struts2 + Hibernate Web App中跨多个dao方法使用同一会话对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了简单起见,我在下面的代码中省略了许多细节.
我的实现正确吗?
此实现有任何弊端吗?
有没有更好的方法来实现呢?

I have omitted many details from the code below just to keep it simple.
Is my implementation right?
Is there any downside of this implementation?
Is there a better way of implementing the same?

MyAction.java

class MyAction {
  public String execute() {
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();

    try {

      UserLoginDAO uldao = new UserLoginDAOImpl();
      uldao.firstMethod(session);
      List l = uldao.secondMethod(session);
      tx.commit();

    } catch(HibernateException ex) {
      if(tx != null) tx.rollback();
    } finally {
      session.close();
    }
    //statements
  }
}

UserLoginDAOImpl.java

class UserLoginDAOImpl implements UserLoginDAO{
  public void firstMethod(session) {
    //statements
    session.save(something);
  }

  public List secondMethod(session) {
    //statements
    List lst = session.createQuery("something").list(); 
    //statements
  }
}

UserLoginDAO.java

interface UserLoginDAO {
  public void firstMethod(session);
  public List secondMethod(session);
}

推荐答案

我的实现对吗?

Is my implementation right?

这是题外话.顺便说一句,看起来不错.

This is off-topic here. BTW it seems fine.

此实现是否有缺点?

Is there any downside of this implementation?

此实现称为视图中开放会话(OSIV)模式",通常称为 Anti -Pattern.

This implementation is called Open Session In View (OSIV) Pattern, often referred as Anti-Pattern.

优点

是否有更好的方法来实现?

Is there a better way of implementing the same?

更好是主观的,因此说哪个比主要基于意见的哪个更好.

Better is subjective, hence saying which is better than which other would be primarily opinion based.

分开更好"并回答还有其他处理事务的方式":从JAVA EE 6开始,事情发生了明智的改变……如果您正在使用它,则将Hibernate用作JPA2实现(相反,作为原始的Hibernate),然后看看EJB3.1(或带有Interceptor的CDI)中的EntityManager和容器管理的事务.

Leaving the "better" apart and answering just to "are there other ways to handle transactions": from JAVA EE 6, things are changed sensibly... if you are using it, then use Hibernate as JPA2 implementation (instead that as raw Hibernate) and take a look at EntityManager and container managed transaction in EJB3.1 (or CDI with Interceptor).

这篇关于如何在Struts2 + Hibernate Web App中跨多个dao方法使用同一会话对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆