2013-04-02 154 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

這就是我所做的。 –