使用spring MVC + hibernate保存数据时,HibernateTemplate对象为null

时间:2019-02-18 19:12:09

标签: spring hibernate maven model-view-controller

我正在尝试使用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");
        }
    } 
}

ApplicationContext.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;
    }

0 个答案:

没有答案