I want to do: @Autowire Session session
. For hibernate 3, the process is described here. it uses ...hibernate3.SessionFactoryUtils.getSession. but in spring 3.2 there is no such method in ...hibernate4.SessionFactoryUtils
Asked
Active
Viewed 5,743 times
2
-
You can inject `SessionFactory` and use `sessionFactory.getCurrentSession()` – Ori Dar Apr 02 '13 at 13:25
-
2yes, i know but it's just... too verbose. if i can inject entityManager with jpa then i should be able to inject session with some proxy mechanism. i just don't know how... yet :) – piotrek Apr 03 '13 at 08:46
1 Answers
4
Great changes have taken place in Spring3.x, a few days ago I met the same problem, Through the offical document we know that Spring won't provide HibernateTemplate and HibernateDaoSupport any longer, we are advised to use Hibernate pure API, and about your confusion here is my solution:
first, define a sessionFactory bean in applicationContext.xml,
<!-- 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>
and then, in your DAO
@Autowired
@Qualifier("sessionFactory")
private SessionFactory sessionFactory;
public Session getSession() {
return sessionFactory.getCurrentSession();
}
in this way you'll get the hibernate session, then do what you want, just enjoy it:)

Hunter Zhao
- 4,589
- 2
- 25
- 39