Tomasz 是对的,但我相信使用“new”创建对象实例并不符合 Spring 概念:
我认为你需要这样做:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.vanilla.objects.Student</value>
<value>com.vanilla.objects.Address</value>
</list>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
然后你可以在你的 Spring bean 中使用它:
@Autowired
SessionFactory sessionFactory;
然后在你的方法里面:
Session session = sessionFactory.getCurrentSession();