如何在Spring中的控制器方法中使用Hibernate

如何在Spring中的控制器方法中使用Hibernate,spring,hibernate,model-view-controller,servlets,controller,Spring,Hibernate,Model View Controller,Servlets,Controller,我用STS创建了一个新的MVC模板项目,并添加了所有依赖项以支持Hibernate 这是我的root-context.xml文件: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.

我用STS创建了一个新的MVC模板项目,并添加了所有依赖项以支持Hibernate

这是我的root-context.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- Root Context: defines shared resources visible to all other web components -->

<jdbc:embedded-database id="dataSource" type="H2"> 
    <jdbc:script location="classpath:schema.sql"/> 
    <jdbc:script location="classpath:test-data.sql"/> 
</jdbc:embedded-database>   

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

<bean id="contactDao" class="com.server.dao.impl.ContactDaoImpl">
    <property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="com.server.model" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
            <prop key="hibernate.max_fetch_depth">3</prop>
            <prop key="hibernate.jdbc.fetch_size">50</prop>
            <prop key="hibernate.jdbc.batch_size">10</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean>  
我假设当web应用程序在服务器上启动时,框架会自动实例化root-context.xml中声明的bean

我的问题是:如何获取对ContactDao对象实例的引用? 即:如何在数据库上执行操作

有人能帮我吗


谢谢

您需要使用注释将
ContactDao
注入控制器:

@Autowired 
public void setContactDao(ContactDao contactDao) {
    ...
}
使用接口(我猜它是ContactDao),这样您就可以更改实现(可能对测试有用)

现在,您可以使用
contactDao
object使用联系人DAO方法


有关自动连线的更多信息,请参阅

您需要确保您的app conext设置为Anotion驱动的Tootanks,这就是问题所在:)
@Autowired 
public void setContactDao(ContactDao contactDao) {
    ...
}