在使用SSH框架的时候,运行时遇到这么一个错:Property 'sessionFactory' is required
我猜测是配置有问题,但不知道错在哪。
异常信息:
Messages:   Property 'sessionFactory' is required    
File:   org/springframework/orm/hibernate3/HibernateAccessor.java   
Line number:   314 Eclipse下 Struts2.3 + Spring3.0 + Hibernate3.6 ,这是导入的jar包:
applicationContext.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"  
       xsi:schemaLocation="http://www.springframework.org/schema/beans   
                           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="jdbcUrl" value="jdbc:sqlserver://localhost:1433;databaseName=test"></property>
<property name="user" value="sa"></property>
<property name="password" value="123"></property>
</bean>
<!-- Hibernate sessionFactory创建 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- Hibernate属性 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
<prop key="hibernate.show_sql">true</prop> 
</props>
</property>
<!-- 映射文件 -->
<property name="mappingResources">
<list>
                  <value>../User.hbm.xml</value>
                </list>
        </property>
</bean>

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<constructor-arg>
<ref local="sessionFactory" />
</constructor-arg>
</bean>
    <bean id="transactionManager"
            class="org.springframework.orm.hibernate3.HibernateTransactionManager">
     <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <bean id="userDao" class="com.test.dao.impl.UserDaoImpl" scope="prototype">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <bean id="registerAction" class="com.test.actions.RegisterAction" scope="prototype">
        <property name="ud" ref="userDao"></property>
    </bean>
</beans>UserDaoImpl.java
package com.test.dao.impl;import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;import com.test.entity.vo.User;
import com.test.interfaces.UserDao;public class UserDaoImpl implements UserDao{ private HibernateTemplate hibernateTemplate = null;
private SessionFactory sessionFactory ;

public SessionFactory getSessionFactory() {
return sessionFactory;
} public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
} public HibernateTemplate getHibernateTemplate() {
if(hibernateTemplate == null){
hibernateTemplate = new HibernateTemplate(sessionFactory);
}
return hibernateTemplate;
}

@Override
public Long addUser(User user) {
// TODO Auto-generated method stub
return (Long)getHibernateTemplate().save(user);
}
}RegisterAction.java
package com.test.actions;import com.opensymphony.xwork2.ActionSupport;
import com.test.dao.impl.UserDaoImpl;
import com.test.entity.vo.User;
import com.test.interfaces.UserDao;public class RegisterAction extends ActionSupport{
/**
 * 
 */
private static final long serialVersionUID = 1L;
private String username;
private String password;
private UserDao ud = new UserDaoImpl();

public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserDao getUd() {
return ud;
}
public void setUd(UserDao ud) {
this.ud = ud;
}

public String execute() throws Exception{
User user = new User();
user.setUsername(username);
user.setPassword(password);
ud.addUser(user);
return SUCCESS;
}
}

解决方案 »

  1.   

    让userDaoImpl继承HibernateDaoSupport
    public class userDaoImpl extends HibernateDaoSupport
    再注入sessionfactory
      

  2.   

     Dao 要继承 HibernateDaoSupport类。
      

  3.   

    private UserDao ud = new UserDaoImpl();
        public UserDao getUd() {
            return ud;
        }
        public void setUd(UserDao ud) {
            this.ud = ud;
        }修改为
    private UserDao userDao;//这里一定不要使用 new UserDaoImpl()
    public void setUserDao(UserDao userDao) {
    xxxxx
    }
    xxxGetUserDao
      

  4.   


    package com.unite.dao.impl;import java.io.Serializable;
    import java.lang.reflect.ParameterizedType;
    import java.util.ArrayList;
    import java.util.List;
    import org.hibernate.Query;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.orm.hibernate3.SessionFactoryUtils;
    import com.unite.dao.BaseDao;
    import com.unite.dao.PageDao;
    import com.unite.entity.PageModel;/**
     * @see 访问数据库的基类dao实现类
     * @version 1.0
     * */
    public abstract class BaseDaoImpl<T extends Serializable> extends PageDao implements BaseDao<T>  {

    @Autowired
    private SessionFactory sessionFactory;
    private Session session;

    // 保存记录
    public T add(T entity) {
    getSession().save(entity);
    return entity;
    }

    // 修改记录
    public T edit(T entity) {
    getSession().update(entity);
    return entity;
    } // 删除记录
    public T del(Serializable id) {
    T entity = get(id);
    getSession().delete(entity);
    return entity;
    } // 根据ID获得记录
    @SuppressWarnings("unchecked")
    public T get(Serializable id) {
    try {
    return (T) getSession().get(getThisClass(), id);
    } catch (Exception e) {
    return null;
    }
    }

    // 获得表中的所有的实体
    @SuppressWarnings("unchecked")
    public List<T> getBeans() {
    String class1 = getThisClass().toString();
    String entity = class1.substring(class1.lastIndexOf(".") + 1);
    return (List<T>) getList("from " + entity + " order by id", null);
    }

    // 获得表中的下一个ID的值
    public Long getNextId() {
    Long result = 0l;
    try {
    String class1 = getThisClass().toString();
    String entity = class1.substring(class1.lastIndexOf(".") + 1);
    Object value = getObject("select max(id) from " + entity, null);
    if (null != value) {
    result = Long.parseLong(value.toString()) + 1;
    } else {
    result = 1l;
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    return result;
    } /**
     * @see 从数据库中获得一个实体类的集合或一列值
     * @param hql hql语句
     * @param args 参数列表(可以为null)
     * @return List  不会为null
     */
    @SuppressWarnings("unchecked")
    public List getList(String hql, Object[] args) {
    try {
    return getQuery(hql, args).list();
    } catch (Exception e) {
    e.printStackTrace();
    return new ArrayList();
    }
    } /**
     * @see 从数据库中获得一个实体或一个值
     * @param hql hql语句
     * @param args 参数列表(可以为null)
     * @return Object
     */
    @SuppressWarnings("unchecked")
    public Object getObject(String hql, Object[] args) {
    List list = getList(hql, args);
    if (list.size() > 0) {
    return list.get(0);
    }
    return null;
    } /**
     * @see 判断真假(数据库是否有这个记录)
     * @param hql hql语句必须是select count(*) from ...
     * @param args 参数列表(可以为null)
     * @return Boolean
     */
    public Boolean validate(String hql, Object[] args) {
    try {
    Object value = getObject(hql, args);
    if (null != value && Integer.parseInt(value.toString()) > 0) {
    return true;
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    return false;
    } /**
     * @see 获得分页
     * @param hql hql语句必须是select * from ...或者from ...
     * @param args 参数列表(可以为null)
     * @param pageIndex 当前页数
     * @param radix 分页的基数
     * @return PageModel
     * */
    public PageModel getPage(String hql, Object[] args, int pageIndex, int radix) {
    try {
    String countHql = "";
    if (hql.indexOf("*") != -1) {
    countHql = hql.replace("*", "count(*)");
    } else {
    countHql = "select count(*) " + hql;
    }
    Integer amount = Integer.parseInt(getObject(countHql, args).toString());
    PageModel model = getPageModel(amount, pageIndex, radix, radix);
    Query query = getQuery(hql, args);
    query.setFirstResult(model.getStart());
    query.setMaxResults(radix);
    model.setList(query.list());
    return model;
    } catch (Exception e) {
    e.printStackTrace();
    return null;
    }
    }

    /**
     * @see 其他操作(增删改返回受影响的行数)
     * @param hql hql语句
     * @param args 参数列表(可以为null)
     * @return Object
     */
    public Integer other(String hql, Object[] args) {
    try {
    return getQuery(hql, args).executeUpdate();
    } catch (Exception e) {
    e.printStackTrace();
    return 0;
    }
    }

    /**
     * @see 搜索引擎
     * @param hql hql语句
     * @return List
     */
    @SuppressWarnings("unchecked")
    public List<String> self(String hql) {
    try {
    Query query = getQuery(hql, null);
    query.setFirstResult(0);
    query.setMaxResults(15);
    return query.list();
    } catch (Exception e) {
    e.printStackTrace();
    return new ArrayList<String>();
    }
    }

    // 获得session
    private Session getSession() {
    if (null == session) {
    session = SessionFactoryUtils.getSession(sessionFactory, true);
    }
    return session;
    }

    // 获得Query
    private Query getQuery(String hql, Object[] args) {
    Query query = getSession().createQuery(hql);
    if (null != args && args.length > 0) {
    for (int i = 0; i < args.length; i++) {
    query.setParameter(i, args[i]);
    }
    }
    return query;
    } // 获得class
    @SuppressWarnings("unchecked")
    private Class<T> getThisClass() {
    return (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    }package com.unite.dao.impl;import java.util.List;
    import org.springframework.stereotype.Service;
    import com.unite.dao.UserDao;
    import com.unite.entity.PageModel;
    import com.unite.entity.User;/**
     * @version 1.0
     * 用户的dao接口实现类
     */
    @Service
    public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao { // 用户登录
    public Boolean login(String userName, String password) {
    return validate("select count(*) from User where userName=? and password=?", new Object[]{ userName, password });
    } // 所有用户分页查询
    public PageModel getPage(Integer pageIndex, Integer radix) {
    return getPage("from User", null, pageIndex, radix);
    } // 更新用户
    public Integer updation(User user) {
    return other("update User set userName=?,password=? where id=?", new Object[]{ user.getUserName(), user.getPassword(), user.getId() });
    } // 检索用户名
    public List<String> selfion(String word) {
    return self("select userName from User where userName like '" + word + "%'");
    } // 根据用户名获得用户
    public User getUser(String userName) {
    return (User) getObject("from User where userName=?", new Object[]{ userName });
    }

    }
    <?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:jee="http://www.springframework.org/schema/jee" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.directwebremoting.org/schema/spring-dwr http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd
    " default-lazy-init="true" default-autowire="byName">

    <context:component-scan base-package="com.unite" />

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="com.mysql.jdbc.Driver" />
    <property name="jdbcUrl" value="jdbc:mysql://localhost/test?characterEncoding=UTF-8" />
    <property name="user" value="root" />
    <property name="password" value="123456" />
    <property name="autoCommitOnClose" value="true" />
    <property name="maxStatements" value="100" />
    <property name="checkoutTimeout" value="5000" />
    <property name="idleConnectionTestPeriod" value="3000" />
    <property name="initialPoolSize" value="3" />
    <property name="minPoolSize" value="3" />
    <property name="maxPoolSize" value="8" />
    <property name="maxIdleTime" value="7200" />
    <property name="acquireIncrement" value="5" />
    <property name="maxIdleTimeExcessConnections" value="1800" />
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="mappingDirectoryLocations">
    <list>
    <value>classpath:/config/hibernate</value>
    </list>
    </property>
    <property name="hibernateProperties">
    <value>
    hibernate.jdbc.batch_size=30
    hibernate.show_sql=true
    hibernate.format_sql=false
    hibernate.cache.use_query_cache=false
    hibernate.cache.use_second_level_cache=false
    hibernate.dialect=org.hibernate.dialect.MySQLDialect
    <!-- hibernate.hbm2ddl.auto=update -->
    </value>
    </property>
    </bean> <tx:annotation-driven transaction-manager="transactionManager" />
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!--  -->
    <dwr:configuration />
    <dwr:controller id="dwrController" debug="true" />
    <dwr:url-mapping />
    <dwr:annotation-scan base-package="com.unite" scanRemoteProxy="true" />

    </beans>
      

  5.   

    加上以后,在调用getHibernateTemplate().save(user)时报了异常java.lang.NullPointerException 
      

  6.   

    配置文件里
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">         <constructor-arg>             <ref local="sessionFactory" />         </constructor-arg>     </bean> 
    用<property>标签包含“sessionFactory”试试
    如果继承了HibernateDaoSupport就可以直接Session session=getSession();貌似就不需要管SessionFactory了
      

  7.   

    配置文件里
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">         <constructor-arg>             <ref local="sessionFactory" />         </constructor-arg>     </bean> 
    用<property>标签包含“sessionFactory”试试
    如果继承了HibernateDaoSupport就可以直接Session session=getSession();貌似就不需要管SessionFactory了
      

  8.   

    终于找到哪里错了,因为我最先用的是struts2,在配置struts.xml时,registerAction的class是com.test.actions.RegisterAction,而后来加入spring以后,需要把这个class和applicationContext.xml里registerAction的id改成一样的问题解决
    多谢各位大虾!