2013-04-02 42 views
1

我想要做的:@Autowire Session session。对于休眠3,该过程描述为here。它使用... hibernate3.SessionFactoryUtils.getSession。但在春天3.2没有这样的方法... hibernate4.SessionFactoryUtilsautowire与春季休眠3和休眠4

+0

你可以注入'SessionFactory'和使用'sessionFactory.getCurrentSession()' –

+1

是的,我知道但只是......太冗长。如果我可以用jpa注入entityManager,那么我应该可以注入一些代理机制的会话。我只是不知道如何... :) :) – piotrek

回答

3

Spring3.x发生了很大的变化,前几天我遇到了同样的问题,通过官方文档我们知道Spring赢得了'牛逼的HibernateTemplate提供和HibernateDaoSupport的任何更长的时间,我们建议使用Hibernate纯API,并约在这里你的困惑是我的解决方案:

首先,定义applicationContext.xml中一个SessionFactory豆,

<!-- sessionFactory --> 
    <bean id="sessionFactory" 
      class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
     <property name="packagesToScan"> 
      <list> 
       <value>com.bbs.*.entity</value> 
      </list> 
     </property> 
     <property name="hibernateProperties"> 
      <props> 
       <prop key="hibernate.dialect"> 
        ${hibernate.dialect} 
       </prop> 
       <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> 
       <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> 
       <prop key="hibernate.connection.autocommit">${hibernate.connection.autocommit}</prop> 
       <prop key="hibernate.connection.url">jdbc:mysql://localhost/bbs</prop> 
       <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop> 
       <prop key="hibernate.connection.username">root</prop> 
       <prop key="hibernate.connection.password">123456</prop> 
      </props> 
     </property> 
     <property name="dataSource"> 
      <ref bean="dataSource" /> 
     </property> 
    </bean> 

,然后,在你的DAO

@Autowired 
@Qualifier("sessionFactory") 
private SessionFactory sessionFactory; 

public Session getSession() { 
    return sessionFactory.getCurrentSession(); 
} 
这样你会得到一个Hibernate Session

,那么你想要什么,只是享受它:)

+0

这就是我所做的。 –