在进行Spring零配置环境搭建的过程中,很多人会遇到这个问题'sessionFactory' or 'hibernateTemplate' is required。
下面我们从如下几点来排查这个问题出现的原因:
1.是否正确配置sessionFactory
<bean name="sessionFactory" id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 指定映射定义--> <property name="mappingLocations"> <list> <value>classpath*:/**/entity/*.hbm.xml</value> </list> </property> <!--指定Hibernate属性 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop> <prop key="hibernate.connection.provider_class">example.util.DruidConnectionProvider</prop> <!--<prop key="hibernate.jdbc.factory_class">example.util.jdbc.BatchingBatcherFactory</prop>--> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.autoReconnect">true</prop> <!-- Hibernate JDBC and Connection Properties --> <prop key="hibernate.jdbc.batch_size">50</prop> <prop key="hibernate.connection.autocommit">false</prop> <prop key="hibernate.connection.release_mode">auto</prop> <prop key="hibernate.bytecode.use_reflection_optimizer">false</prop> <prop key="javax.persistence.validation.mode">none</prop> </props> </property> </bean>
2.如果你的dao继承了HibernateDaoSupport,那你要检查下,你有没有为HibernateDaoSupport注入sessionFactory
@Resource(name="sessionFactory") public void setSessionFactoryOverride(SessionFactory sessionFactory) { super.setSessionFactory(sessionFactory); }
3.如果上述配置都没问题,你需要检查下你是否开启了Spring自动装配,如果没有开启,那么在注解的时候会注入一个空的sessionFactory,hibernate检查的时候就会报错了,在Spring配置文件中加入byName的方式注入bean后就可以正常的使用注解了。
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd" default-autowire="byName" default-lazy-init="false">