qinkaiyuan94
ky与你
2016-05-12 10:06
采纳率: 90%
浏览 1.2k

spring4.14+hibernate4.3整合,web运行正常,junit测试报错;

之前web启动的时候也报这个错误,然后在web.xml里面加了这个filter,就好了。

可是现在用junit测试,没办法读取web.xml里面的配置,所以还报了这个错,

别问我为什么要junit测试,就是想知道 junit测试的时候这种情况怎么解决。 下面附代码


SpringOpenSessionInViewFilter
org.springframework.orm.hibernate4.support.OpenSessionInViewFilter


SpringOpenSessionInViewFilter
/*

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

6条回答 默认 最新

  • qinkaiyuan94
    ky与你 2016-05-12 10:08

    web.xml

     <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    
        <display-name>zhuge3</display-name>
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring*.xml</param-value>
        </context-param>
        <!-- 监听servletContext,启动contextConfigLocation中的spring配置信息 -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    
    
        <!-- <listener>
            <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
        </listener> -->
        <filter>
            <filter-name>encodingFilter</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <param-name>encoding</param-name>
                <param-value>utf-8</param-value>
            </init-param>
            <init-param>
                <param-name>forceEncoding</param-name>
                <param-value>true</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>encodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
        <!-- openSessionInView配置 作用是延迟session关闭到view层 -->
        <filter>
           <filter-name>SpringOpenSessionInViewFilter</filter-name>
           <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
         </filter>
          <filter-mapping>
            <filter-name>SpringOpenSessionInViewFilter</filter-name>
            <url-pattern>/*</url-pattern>
          </filter-mapping>
        <!-- <init-param>
            <param-name>singleSession</param-name>
            <param-value>true</param-value>
            </init-param>
            <init-param>
            <param-name>FlushMode</param-name>
            <param-value>AUTO</param-value>
            </init-param> -->
        <servlet>
            <servlet-name>mvc-dispatcher</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <!-- 默认配置地址webinf/mvc-dispatcher-servlet.xml -->
                <!-- 不配置的话 此处配置的是SpringMVC的配置文件 -->
                <param-value>classpath:spring-mvc.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>mvc-dispatcher</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
        <!-- 配置session超时时间,单位分钟 -->
        <session-config>
            <session-timeout>30</session-timeout>
        </session-config>
    
        <welcome-file-list>
            <welcome-file>/index.jsp</welcome-file>
        </welcome-file-list>
    </web-app>
    
    
    点赞 评论
  • qinkaiyuan94
    ky与你 2016-05-12 10:09

    spring-hibernate.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:tx="http://www.springframework.org/schema/tx"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xsi:schemaLocation="  
            http://www.springframework.org/schema/beans   
            http://www.springframework.org/schema/beans/spring-beans-4.1.xsd   
            http://www.springframework.org/schema/tx   
            http://www.springframework.org/schema/tx/spring-tx-4.1.xsd  
            http://www.springframework.org/schema/aop   
            http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
    
        <!-- 配置数据源 c3p0 -->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
            destroy-method="close">
            <property name="driverClass" value="${jdbc.driver}" />
            <property name="jdbcUrl" value="${jdbc.url}" />
            <property name="user" value="${jdbc.username}" />
            <property name="password" value="${jdbc.password}" />
    
            <!-- 请求超时时间 -->
            <property name="checkoutTimeout" value="30000" />
            <!-- 每60秒检查所有连接池中的空闲连接。默认值: 0,不检查 -->
            <property name="idleConnectionTestPeriod" value="30" />
            <!-- 连接数据库连接池最大空闲时间 -->
            <property name="maxIdleTime" value="30" />
            <!-- 连接池初始化连接数 -->
            <property name="initialPoolSize" value="5" />
            <property name="minPoolSize" value="5" />
            <property name="maxPoolSize" value="20" />
            <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 -->
            <property name="acquireIncrement" value="5" />
        </bean>
    
        <!-- 配置hibernate的SessionFactory -->
        <bean id="sessionFactory"
            class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
            <!-- 注入数据源 相关信息看源码 -->
            <property name="dataSource" ref="dataSource" />
            <!-- hibernate配置信息 -->
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                    <prop key="hibernate.show_sql">true</prop>
                    <prop key="hibernate.format_sql">true</prop>
                    <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
                    <!-- <prop key="hibernate.hbm2ddl.auto">update</prop> -->
                    <!-- <prop key=" hibernate.connection.autocommit">true</prop>
                    <prop key="hibernate.connection.release_mode">auto</prop> -->
                    <!-- 开启二级缓存 ehcache -->
                    <!-- <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
                    <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
                    <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>
                    <prop key="hibernate.cache.provider_configuration_file_resource_path">${hibernate.cache.provider_configuration_file_resource_path}
                    </prop> -->
                </props>
            </property>
            <!-- <property key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</property>
            <property name="current_session_context_class">thread</property> -->
            <!-- 扫描hibernate注解配置的entity -->
            <property name="packagesToScan" value="com.qky.entity" />
        </bean>
        <!-- <bean id="jdbcTemplate"
            class="org">
            <property name="sessionFactory" ref="sessionFactory" />
        </bean> -->
        <!-- <bean id="hibernateTemplate"
            class="org.springframework.orm.hibernate4.HibernateTemplate">
            <property name="sessionFactory" ref="sessionFactory" />
        </bean> -->
        <!-- 配置事务管理器 -->
        <bean id="transactionManager"
            class="org.springframework.orm.hibernate4.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory" />
        </bean>
    
        <!-- 配置事务增强处理Bean,指定事务管理器 -->
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <!-- 配置详细事务处理语义 -->
            <tx:attributes>
                <tx:method name="insert*" propagation="REQUIRED" />
                <tx:method name="update*" propagation="REQUIRED" />
                <tx:method name="delete*" propagation="REQUIRED" />
                <tx:method name="save*" propagation="REQUIRED" />
                <tx:method name="add*" propagation="REQUIRED" />
                <tx:method name="add" propagation="REQUIRED" />
                <tx:method name="get*" propagation="NOT_SUPPORTED" read-only="true" />
                <tx:method name="find*" propagation="NOT_SUPPORTED" read-only="true" />
                <tx:method name="select*" propagation="NOT_SUPPORTED" read-only="true" />
                <tx:method name="load*" propagation="NOT_SUPPORTED" read-only="true" />
                <!-- 其他采用默认事务方式 -->
                <tx:method name="*" />
            </tx:attributes>
        </tx:advice>
        <!-- Spring aop事务管理 -->
        <aop:config>
            <!-- 配置切入点 -->
            <aop:pointcut id="txPointcut"
                expression="execution(* com.qky.service.*.*.*(..))" />
    <!--            expression="execution(* com.qky.service..*Impl.*(..))" /> -->
                <!-- expression="execution(* com.qky.service..*Impl.*(..))" /> -->
            <!-- 指定在txAdvice切入点应用txAdvice事务增强处理 -->
            <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
        </aop:config>
        <!-- <tx:annotation-driven transaction-manager="transactionManager"/> -->
    </beans>  
    
    点赞 评论
  • qinkaiyuan94
    ky与你 2016-05-12 10:11

    所有dao层继承这个dao层,得到currentSession.xml

     package com.qky.dao.utilDao;
    
    import javax.annotation.Resource;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.springframework.stereotype.Repository;
    
    @Repository
    public class CurrentSessionDao{
        @Resource
        SessionFactory sessionFactory;
    
        protected final Session currentSession(){
            return sessionFactory.getCurrentSession();
        }
    
    }
    
    
    点赞 评论
  • qinkaiyuan94
    ky与你 2016-05-12 10:12

    baseDaoImpl

     package com.qky.dao.baseDao.impl;
    
    import java.io.Serializable;
    import java.lang.reflect.ParameterizedType;
    import java.math.BigInteger;
    import java.util.List;
    import java.util.Map;
    
    import org.hibernate.Query;
    import org.hibernate.Session;
    import org.hibernate.metadata.ClassMetadata;
    import org.hibernate.type.Type;
    import org.springframework.stereotype.Repository;
    
    import com.qky.dao.baseDao.BaseDao;
    import com.qky.dao.utilDao.CurrentSessionDao;
    import com.qky.entity.User;
    import com.qky.util.PageUtil;
    
    @Repository
    public class BaseDaoImpl<T> extends CurrentSessionDao implements BaseDao<T>{
        @SuppressWarnings("unchecked")
        public PageUtil getUserListByPageUtil(int pageIndex, int pageSize,T t) {
            int beginRow=(pageIndex-1)*pageSize;
            List<User> plist=(List<User>) currentSession()
                    .createCriteria(t.getClass())
                    .setFirstResult(beginRow)
                    .setMaxResults(pageSize).list();
            Object count=currentSession().createSQLQuery("select count(0) from user").uniqueResult();
            PageUtil pageUtil=new PageUtil(pageIndex,pageSize,Integer.valueOf(count.toString()));
            pageUtil.setPlist(plist);
            return pageUtil;
        }
        public T add(T t){
            currentSession().save(t);
            return  t;
        }
        public void update(T t){
            currentSession().update(t);
        }
    
        public void merge(T t){
            currentSession().merge(t);
        }
        public void delete(T t) {
            currentSession().delete(t);
        }
    
        public T get(Class<T> entityClass, Serializable id) {
            T ret = (T) currentSession().get(entityClass, id);
            return ret;
        }
        public void deleteById(Serializable id){
            T ret = this.get(this.getEntityClass(), id);
            if (ret != null){
                delete(ret);
            }
        }
    
    //  @Override
    //  public List<T> findAll() throws Exception {
    //      String hql = "from "+this.getEntityClassName();
    //      return this.queryForList(hql, null).getResultList();
    //      
    //  }
    //  @Override
    //  public PageList<T> findAll(PageBean pageBean) throws Exception {
    //      String hql = "from "+this.getEntityClassName();
    //      return (PageList<T>)this.queryForList(hql, pageBean);
    //      
    //  }
        @SuppressWarnings("unchecked")
        public T findById(Serializable id){
            return (T)currentSession().get(getEntityClassName(), id);
    
        }
    //  public T findForObject(final T entity){
    //      PageList<T> pageList = findForList(entity, null);
    //      if(pageList != null && pageList.getResultList() != null && !pageList.getResultList().isEmpty()){
    //          return pageList.get(0);
    //      }
    //      return null;
    //  }
    //  @SuppressWarnings("unchecked")
    //  public PageList<T> findForList(final T entity, final PageBean pageBean){
    //      DetachedCriteria detachedCriteria = DetachedCriteria.forClass(entity.getClass()).add(Example.create(entity));
    //      List<?> list = null;
    //      if(!PageBean.isEmpty(pageBean)) {
    //          list = hibernateTemplate.findByCriteria(detachedCriteria, pageBean.getLimit(), pageBean.getOffset());
    //          Criteria criteria = detachedCriteria.getExecutableCriteria(hibernateTemplate.getSessionFactory().getCurrentSession());
    //          Long totalCount = (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();
    //          pageBean.setTotalCount(totalCount);
    //      } else {
    //          list =hibernateTemplate.findByCriteria(detachedCriteria);
    //      }
    //      return new PageList<T>((List<T>)list, pageBean);
    //  }
    
        // 
    
    //  /**
    //   * 单对象查询
    //
    //   * @param hql
    //   * @param objects
    //   * @return
    //   * 2014年3月21日 下午2:08:26
    //   */
    //  protected T queryForObject(final String hql, final Object ... objects){
    //      PageList<T> pageList = this.queryForList(hql, null, null, objects);
    //      if(pageList != null && pageList.isEmpty()){
    //          return pageList.get(0);
    //      }
    //      return null;
    //  }
    
        /**
        * 执行查询结果集
    
        * @param hql
        * @param page
        * @param pageSize
        * @param objects
        * @return
        * 2014年3月21日 下午2:08:09
        */
    //  protected PageList<T> queryForList(final String hql, final PageBean pageBean, final Object ... objects ){
    //      return hibernateTemplate.execute(new HibernateCallback<PageList<T>>() {
    //          @SuppressWarnings("unchecked")
    //          @Override
    //          public PageList<T> doInHibernate(Session session) throws HibernateException {
    //              Query createQuery = createQuery(session, hql, objects);
    //              List<T> list = null;
    //              if(pageBean != null){
    //                  createQuery.setFirstResult(pageBean.getLimit());   
    //                  createQuery.setMaxResults(pageBean.getOffset());  
    //                  list = createQuery.list();
    //                  String countHql = null;
    //                  if(StringUtils.containsIgnoreCase(hql, "from")){
    //                      countHql = "select count(0) "+StringUtils.substring(hql, StringUtils.indexOfIgnoreCase(hql, "from"));
    //                  }
    //                  Query countQuery = createQuery(session, countHql, objects);
    //                  List<Long> countList = countQuery.list();
    //                  Long totalCount = 0L;
    //                  if(countList != null && countList.size() > 0){
    //                      totalCount =countList.get(0);
    //                  }
    //                  pageBean.setTotalCount(totalCount);;
    //              } else {
    //                  list = createQuery.list();
    //              }
    //              return new PageList<T>(list, pageBean);
    //          }
    //          
    //      });
    //  }
    
        /**
        * 执行查询以外的操作
        * @param hql
        * @param objs
        * 2014年3月21日 上午11:42:19
        */
        /*protected Integer executeUpdate(final String hql, final Object ... objects){
            return currentSession().execute(new HibernateCallback<Integer>() {
                public Integer doInHibernate(Session session) throws HibernateException {
                    Query createQuery = createQuery(session, hql, objects);
                    return createQuery.executeUpdate();
                }
            });
        }*/
        /**
        * 得到泛型中的实体类型
    
        * @return
        * 2014年3月18日 下午2:32:35
        */
        protected Class<T> getEntityClass(){
            @SuppressWarnings("unchecked")
            Class<T> entityClass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
            return entityClass;
        }
        /**
        * @Author: Charles
        * @Description: 获取表主键类型
        * @param clazz
        * @return Type:
        */
        public Type getPkType() {
            ClassMetadata meta = currentSession().getSessionFactory().getClassMetadata(getEntityClass());
            return meta.getIdentifierType();
        }
        /**
        * 获取主键名
    
        * @return
        * 2014年3月21日 下午2:42:49
        */
        public String getPkColunmName(){
            ClassMetadata meta = currentSession().getSessionFactory().getClassMetadata(getEntityClass());
            return meta.getIdentifierPropertyName();
        }
    
    /**
        * 获取实体类型名
    
        * @return
        * 2014年3月18日 下午2:33:01
        */
        protected String getEntityClassName() {
            ClassMetadata meta = currentSession().getSessionFactory().getClassMetadata(getEntityClass());
            return meta.getEntityName();
        }
        /**
        * 返回设置好参数的查询对象
    
        * @param query
        * @param objects
        * 2014年3月21日 下午2:07:56
        */
        private Query createQuery(Session session,String hql, Object ... objects) {
            Query query = session.createQuery(hql);
            if (objects != null){
                for (int i = 0; i < objects.length; i++) {
                    query.setParameter(i, objects[i]);
                }
            }
            return query;
        }
    
        /*@SuppressWarnings("unchecked")
        public List<T> find(String hql, String[] paramNames, Object[] values) {
            List<T> ret = null;
            ret = (List<T>)currentSession().findByNamedParam(hql, paramNames,values);
            return ret;
        }*/
    
        /*@SuppressWarnings("unchecked")
        public List find(final String hql, final Map<String, Object> param, final int pageNo,
                final int pageSize) {
            return currentSession().execute(new HibernateCallback<List>() {
                public List doInHibernate(Session session) throws HibernateException {
                    String shql=hql;
                    if (pageNo == 0&&pageSize!=0) {
                        String sql = "select count(e) ";
                        shql = sql + hql;
                    }
                    Query query = session.createQuery(shql);
                    if (param != null && param.size() > 0) {
                        for (String property : param.keySet()) {
                            if (param.get(property) instanceof List){
                                query.setParameterList(property, (Collection)param.get(property));
                            }else{
                                query.setParameter(property,
                                        param.get(property));
                            }
                        }
                    }
                    if (pageNo != 0 && pageSize != 0) {
                        query.setFirstResult((pageNo - 1) * pageSize);
                        query.setMaxResults(pageSize);
                    }
                    List list = null;
                    try{
                        list = query.list();
                    }catch (HibernateException e) {
                        e.printStackTrace();
                        throw e;
                    }
                    return list;
                }
            });
    
        }*/
    
    @SuppressWarnings("unchecked")
        public List<T> find(final String hql,final Map<String, Object> param) {
            Session session = currentSession().getSessionFactory().getCurrentSession();
            Query query = session.createQuery(hql);
            if (param != null && param.size() > 0) {
                for (String property : param.keySet()) {
                    query.setParameter(property,param.get(property));
                }
            }
            return query.list();
            /*return hibernateTemplate.execute(new HibernateCallback<List>() {
                @Override
                public List<T> doInHibernate(Session session) throws HibernateException {
                    Query query = session.createQuery(hql);
                    if (param != null && param.size() > 0) {
                        for (String property : param.keySet()) {
                            query.setParameter(property,param.get(property));
                        }
                    }
                    return query.list();
                }
            });*/
    
        }
    //
    //  @Override
    //  public List<T> find(String hql) {
    //      return this.queryForList(hql, null).getResultList();
    //  }
    //
    //  @SuppressWarnings("unchecked")
    //  @Override
    //  public List findHql(String hql) {
    //      return this.queryForList(hql, null).getResultList();
    //  }
    
        @SuppressWarnings("unchecked")
        public Object getById(Class c, Serializable id) {
            Object ret = currentSession().get(c, id);
            return ret;
        }
    
        /*public List findHql(final String hql, final Map<String, Object> param) {
            return currentSession().execute(new HibernateCallback<List>() {
                public List<T> doInHibernate(Session session) throws HibernateException {
                    Query query = session.createQuery(hql);
                    if (param != null && param.size() > 0) {
                        for (String property : param.keySet()) {
                            query.setParameter(property,param.get(property));
                        }
                    }
                    return query.list();
                }
            });
        }*/
    
        /*public int updateHql(String hql) {
            return executeUpdate(hql, null);
        }*/
        public List<T> find(String hql) {
            List<T> list = this.find(hql, null);
            return list;
        }
    
        public List findHql(String hql) {
                List list = findHql(hql, null);
                return list;
            }
    
        @Override
        public T addUser(T t) {
            currentSession().save(t);
            return t;
        }
    
        @Override
        public List<T> find(String hql, String[] paramNames, Object[] values) {
            // TODO 自动生成的方法存根
            return null;
        }
    
        @Override
        public List findHql(String hql, Map<String, Object> param) {
            // TODO 自动生成的方法存根
            return null;
        }
    
        @Override
        public int updateHql(String hql) {
            // TODO 自动生成的方法存根
            return 0;
        }
    
    }
    
    点赞 评论
  • qinkaiyuan94
    ky与你 2016-05-12 10:14

    baseService

     package com.qky.service.baseService;
    
    
    import javax.annotation.Resource;
    
    import org.springframework.stereotype.Service;
    
    import com.qky.dao.baseDao.BaseDao;
    import com.qky.util.PageUtil;
    @Service
    public class BaseService<T> {
        @Resource
        BaseDao<T> baseDao;
        public T add(T t) throws Exception{
            baseDao.add(t);
            return t;
        }
        public boolean addUser(T t) {
            try {
                baseDao.addUser(t);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        public PageUtil getUserListByPageUtil(int pageIndex, int pageSize,T t) {
            return baseDao.getUserListByPageUtil(pageIndex, pageSize, t);
        }
    }
    
    
    点赞 评论
  • Mr_li13
    黯雅悸动 2016-05-12 13:05

    把你的Juit改为4.0版本的

    点赞 评论

相关推荐