首页 > 解决方案 > 使用spring MVC+hibernate保存数据时HibernateTemplate对象为null

问题描述

我正在尝试使用 Spring MVC+Hibernate 将数据插入表中。表正在创建,但在 CompanyDao 文件中调用 template.save() 方法时代码抛出异常。请帮助解决这个问题。

我已经测试了公司对象是否为空,但公司对象的所有数据都为空,但模板除外。

文件:CompanyDao.java

import org.springframework.orm.hibernate5.HibernateTemplate;  

public class CompanyDao {  
    HibernateTemplate template;  
    public void setTemplate(HibernateTemplate template) {  
        this.template = template;  
    }  
    //method to save Company  
    public void saveCompany(Company c){

        if(c!=null) {
            template.save(c);
        }
        else {
            System.out.print("company object is null");
        }
    } 
}

应用程序上下文.xml

   <bean id="mysessionFactory"  class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">  
        <property name="dataSource" ref="dataSource"></property>  

        <property name="mappingResources">  
        <list>  
        <value>company.hbm.xml</value>  
         <!-- <value>address.hbm.xml</value> -->
        </list>  
        </property>  

        <property name="hibernateProperties">  
            <props>  
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>  
                <prop key="hibernate.hbm2ddl.auto">update</prop>  
                <prop key="hibernate.show_sql">true</prop>  

            </props>  
        </property>  
    </bean>  

    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">  
    <property name="sessionFactory" ref="mysessionFactory"></property>  
    </bean>  

    <bean id="template" class="dao.CompanyDao">  
    <property name="template" ref="hibernateTemplate"></property>  
    </bean> 

文件控制器:

@RequestMapping("/submitCompanyRegForm")
    public ModelAndView submitCompanyRegForm(@ModelAttribute("companyMo") Company comp)
    {

        CompanyDao companydao = new CompanyDao();
        companydao.saveCompany(comp);

        ModelAndView model = new ModelAndView("submitcompanyreg");


        return model;
    }

标签: springhibernatemavenmodel-view-controller

解决方案


推荐阅读