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

问题描述

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

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

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

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

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

SpringOpenSessionInViewFilter
/*

解决方案

controller

 package com.qky.controller.userController;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.qky.entity.User;
import com.qky.service.baseService.BaseService;
import com.qky.util.PageUtil;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    BaseService<User> userBaseService;

    @RequestMapping("/mvc")
    public String helloMvc(Model map) {
        return "index";
    }
    @RequestMapping("/success")
    public String successMvc(@RequestParam("name") String name,Model map) throws Exception {
        map.addAttribute("name",name);
        User user=new User();
        user.setName(name);
        userBaseService.add(user);
        return "success";
    }
    @RequestMapping("/login")
    public String loginMvc(Model map) {
        return "NewFile";
    }
    @RequestMapping("/show")
    public String showMvc(
            @RequestParam("name") String name,
            @RequestParam("pageIndex") Integer pageIndex,
            @RequestParam("pageSize") Integer pageSize, Model map) throws Exception {
        User user=new User();
        user.setName(name);
        userBaseService.add(user);
        PageUtil pageUtil=userBaseService.getUserListByPageUtil(pageIndex,pageSize,user);
        map.addAttribute(pageUtil);
        return "userShow";
    }
}

解决方案二:

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>

解决方案三:

spring.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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.1.xsd">
    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:config.properties" />
    <!-- <context:annotation-config /> -->
    <!-- 扫描service自动注入为bean -->
    <context:component-scan base-package="com.qky">
        <context:exclude-filter type="annotation"
        expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
</beans>

解决方案四:

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>

解决方案五:

spring-mvc.xml

 <?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
    <!-- 说明可以向 controller里面注入 resource,激活了注解的di -->
    <!-- <context:annotation-config /> -->
    <!-- 自动扫描@Controller注入为bean -->
    <context:component-scan base-package="com.qky.controller">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!-- handlermapping 无需配置,springmvc默认启动 -->
    <!-- DefaultAnnotationHandlerMapping annotation-driven handlerMapping -->
    <!-- 以下为SpringMVC配置 启动基于 dispatcherservlet启用基于annotation的handlermapping -->
    <!-- 扩展了驱动注解,可以将请求参数绑定到控制器参数 -->
    <!-- 以下为SpringMVC配置 -->
    <!-- <mvc:annotation-driven>
        返回json数据,@response使用
        <mvc:message-converters register-defaults="true">
            <bean
                class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>

            </bean>
        </mvc:message-converters> -->
    <mvc:annotation-driven/>
    <!-- 配置静态资源文件处理, js,css,img -->
    <mvc:resources location="/resources/" mapping="/resources/"></mvc:resources>

    <!-- 配置多个viewresolver 可以用多个viewresolver.使用order排序internalresourceviewresolver放在最后 -->
    <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

解决方案六:

所有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();
    }

}

解决方案七:

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

}

解决方案八:

junit运行web测试

解决方案九:

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);
    }
}

解决方案十:

把你的Juit改为4.0版本的

时间: 2024-08-04 10:55:53

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

tomcat启动报错-tomcat 加载ssh,运行服务器的时候报错,请大神赐教!

问题描述 tomcat 加载ssh,运行服务器的时候报错,请大神赐教! 主要是这个错误:java.lang.NoClassDefFoundError: Lorg/hibernate/SessionFactory;比较全的错误如下:信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1cad7d80: defining beans [test

android 启动报错-Android 运行程序有时候经常报错adb

问题描述 Android 运行程序有时候经常报错adb The connection to adb is down, and a severe error has occured. [2013-09-10 16:08:44 - QualityPicture_Client1.3.1.5] You must restart adb and Eclipse. [2013-09-10 16:08:44 - QualityPicture_Client1.3.1.5] Please ensure that

为什么这个代码运行的时候不报错,但是对方计算机收不到消息?请问是VC++没有编译么?

问题描述 为什么这个代码运行的时候不报错,但是对方计算机收不到消息?请问是VC++没有编译么? 为什么这个代码运行的时候不报错,但是对方计算机收不到消息?请问是VC++没有编译么? 解决方案 哪里来的程序,什么代码.有没有说明文档,是不是防火墙限制了. 解决方案二: 你的代码发送的消息是否正确发送过去了,是否有收到

c++-各位大虾, 我想在程序里监视系统上运行的某些程序运行过程中是否报错异常,能实现吗? 怎么实现?

问题描述 各位大虾, 我想在程序里监视系统上运行的某些程序运行过程中是否报错异常,能实现吗? 怎么实现? 对于程序运行过程中卡死已经能检测,但是对于一些弹框类的运行出错却不知道怎么检测,请各位大虾指点迷津; 现在没有C币,如果回答是我想要的,我花钱补上 解决方案 这不就是编写一个华医生么(注:华医生是微软系统上负责处理应用程序崩溃的程序,就是你图上的"xxx已停止工作,Windows正在联机查找解决方案"),这是一个应用程序,是在用户模式下实现的,而并非在内核中实现,其实华医生也可以卸

异常-winform程序运行一段时间报错,弹出一框提示,是什么原因

问题描述 winform程序运行一段时间报错,弹出一框提示,是什么原因 报错内容翻译过来时:未处理的异常发生在你有如果您单击继续,应用程序将忽略此错误并尝试continue.if点击"退出",该应用程序将立即关闭.基础连接已关闭:一个连接,将活着被服务器关闭. 解决方案 只提供这点信息,别人可能帮不到你.所以建议你最好是能通过 Visual Studio 工具进行调试,如果在调试时出现错误,VS 会自动中断到代码中出错的地方. 解决方案二: 你的窗体程序里都运行什么?如果不长的话,把代

tomcat启动报错-空web工程启动tomcat为什么报错?求高手解决

问题描述 空web工程启动tomcat为什么报错?求高手解决 严重: StandardServer.await: create[localhost:8005]: java.net.BindException: Cannot assign requested address: JVM_Bind at java.net.PlainSocketImpl.socketBind(Native Method) at java.net.PlainSocketImpl.bind(Unknown Source)

config-eclipse中,添加web.xml后,tomcat报错。

问题描述 eclipse中,添加web.xml后,tomcat报错. The Tomcat server configuration at ServersTomcat v7.0 Server at localhost-config is missing. Check the server for errors. 解决方案 Tomcat v7.0 Server没启动吧

404-tomcat能正常运行,运行项目的时候报错

问题描述 tomcat能正常运行,运行项目的时候报错 ![图 tomcat也能正常运行,..项目也add到servers上面去了 解决方案 404,tomcat运行着,也不能代表不会404,你访问的地址存在吗,端口号对吗 解决方案二: 404错误是你访问的地址不存在.检查一下你访问的端口和路径对不对: 双击Tomcat v7.0 Server, 解决方案三: 像我的访问地址就是:http://localhost:8081/MessagePush/ 解决方案四: 还有就是你的项目根目录下有没有默认

jsp servlet-jsp跳转到相应的servlet了,但是servlet不运行,也不报错就停在servlet中了

问题描述 jsp跳转到相应的servlet了,但是servlet不运行,也不报错就停在servlet中了 我还故意写上了测试代码 int sign=0; sign=acd.insert(c);//数据库执行插入,成功则返回1 if(sign==0){ response.sendRedirect(request.getContextPath()+""/false.jsp""); }else{ response.sendRedirect(request.getConte