Lazy-loading with Spring HibernateDaoSupport?

穿精又带淫゛_ 提交于 2019-12-08 04:11:17

My question is how the HibernateDaoSupport handles lazy-loading , because after a call to DAO, the Session is closed.

The DAOs don't create/close a Session for each call, they are not responsible for this and this is usually done using the "Open Session in View" pattern (Spring provide a filter or an interceptor for this). But this is for web apps.

In a swing app, one solution is to use long session. You'll have to decide well-defined points at which to close the session to release memory. For small applications, this is usually straightforward and will work. For bigger (i.e. real life apps), the right solution is to use one session per frame/internal frame/dialog. It's harder to manage but will scale.

Some threads you might want to read:

If you are already using Spring you can make use of its Transaction-Declaration. Using this you are able to declare a transaction for a specific method. This keeps the Sessio open for the complete tx.

Declare the Transaction Pointcut

  <!-- this is the service object that we want to make transactional -->
  <bean id="SomeService" class="x.y.service.SomeService"/>

  <tx:advice id="txAdvice" transaction-manager="txManager">
    <!-- the transactional semantics... -->
    <tx:attributes>
      <!-- all methods starting with 'get' are read-only -->
      <tx:method name="get*" read-only="true"/>
      <!-- other methods use the default transaction settings (see below) -->
      <tx:method name="*"/>
    </tx:attributes>
  </tx:advice>

  <!-- ensure that the above transactional advice runs for any execution
      of an operation defined by the FooService interface -->
  <aop:config>
    <aop:pointcut id="MyServicePointcut" expression="execution(* x.y.service.SomeService.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="SomeServiceOperation"/>
  </aop:config>

  <bean id="txManager" class="org.springframework.orm.hibernate.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
  </bean>

Now you can do this lazy keeping the Session open for the complete Method.

public class SomeService()
{
  public Family getFamily()
  {
    Family famA=dao.getFamilyById(familyid);
    //Do some stuff
    List<SubFamily> childrenA=fam.getSubFamiles();
    SubFamily asubfamily=dao.getSubFamily(id,subfamilyid);
    //Do some other stuff
    return asubfamily.getFamily();
  }
}

See Chapter 9 of Springs Tx Reference for further details.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!