开发者社区> 问答> 正文

搭建SSM项目时一直搭建不了mybatis,大家帮帮忙?报错

小弟今天使用maven搭建SSM框架 (springMVC+spring4.0+mybatis3.2)

根据网上很多教程搭建了起来,springmvc可以运行,但是查询数据库始终不行

我的web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name>易额科技自定义后台</display-name>
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/applicationContext-mvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
    	classpath:spring/applicationContext.xml, 
    	classpath:spring/spring-mybatis.xml
    </param-value>
  </context-param>
  
  <!-- 配置Spring字符编码过滤器 -->  
  <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> 
</web-app>



applicationContext-mvc.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"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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-4.0.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
	<!-- 启用spring mvc 注解 -->
	<context:annotation-config></context:annotation-config>
	<mvc:annotation-driven></mvc:annotation-driven>
	
	<!-- 设置使用注解的类所在的包 -->
	<context:component-scan base-package="appmanager.controller"></context:component-scan>
	<!-- 对静态资源文件的访问 -->
    <mvc:resources mapping="*.js" location="*.js" />
    <mvc:resources mapping="*.img" location="*.img" />
    <mvc:resources mapping="*.png" location="*.png" />
    <mvc:resources mapping="/static/" location="/static/**" />
    <!-- web.xml内定义的默认访问 -->
    <mvc:default-servlet-handler/>
    
    
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
    
    <!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 -->
  	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  		<property name="prefix" value="/"></property>
  		<property name="suffix" value=""></property>
  	</bean>
</beans>



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"
	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-4.0.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
	<!-- JDBC配置 -->
	<context:property-placeholder location="classpath:jdbc.properties"/>
	<!-- 扫描service -->
	<context:component-scan base-package="appmanager.service"></context:component-scan>
</beans>



spring-mybatis.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"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	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.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
	
	<!-- 开启自动扫描 -->
	<context:annotation-config></context:annotation-config>
	<!-- 引入JDBC配置文件 -->
	<!-- <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:jdbc.properties"></property>
	</bean> -->
	
	<!-- 配置数据源 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
	
		<property name="driverClassName" value="${driver}" />  
        <property name="url" value="${url}" />  
        <property name="username" value="${username}" />  
        <property name="password" value="${pwd}" />  
        <!-- 初始化连接大小 -->  
        <property name="initialSize" value="${initialSize}"></property>  
        <!-- 连接池最大数量 -->  
        <property name="maxActive" value="${maxActive}"></property>  
        <!-- 连接池最大空闲 -->  
        <property name="maxIdle" value="${maxIdle}"></property>  
        <!-- 连接池最小空闲 -->  
        <property name="minIdle" value="${minIdle}"></property>  
        <!-- 获取连接最大等待时间 -->  
        <property name="maxWait" value="${maxWait}"></property>  
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}"></property>
        
	</bean>
	<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <!-- <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property> -->
        <!-- 自动扫描mapping.xml文件 -->    
        <property name="mapperLocations" value="classpath:appmanager/dao/impl/*.xml" ></property>  
    </bean> 
    <!-- <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
    	<constructor-arg ref="sqlSessionFactory"></constructor-arg>
    </bean>  -->
    <!-- DAO接口所在包名,Spring会自动查找其下的类  配置扫描器-->  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="appmanager.dao" />  
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  
    </bean>  
  
    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->  
    <bean id="transactionManager"  
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    </bean>
    
</beans>



这是我的目录结构


dao文件

appmanager.dao.TestDao 文件


package appmanager.dao;

public interface TestDao {
	public int getcount() ;
}



appmanager.dao.impl.TestDaoMapper.xml 文件



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC   
    "-//mybatis.org//DTD Mapper 3.0//EN"  
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="appmanager.dao.TestDao">
	
	<select id="getcount" resultType="int">
		select count(1) from dual
	</select>
</mapper>



service 文件


appmanager.service.TestService 文件

package appmanager.service;

public interface TestService  {
	public int getcount1() ;
}

appmanager.service.impl.TestServiceImpl 文件

package appmanager.service.impl;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import appmanager.dao.TestDao;
import appmanager.service.TestService;

@Service("TestService")
public class TestServiceImpl implements TestService {
	@Autowired
	private TestDao bean ; 
	@Override
	public int getcount1() {
		System.out.println(bean);
		System.out.println(bean.getcount());
		return bean.getcount();
	}

}



Controller文件

appmanager.controller.Test

package appmanager.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import appmanager.base.WebBase;
import appmanager.service.impl.TestServiceImpl;

@Controller
public class Test {
	
	@RequestMapping("demo")
	public void test(HttpServletResponse res){
		res.setContentType(WebBase.RESPONSECONTENTTYPE_P);
		try {
			res.getWriter().print("nihao 1");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(12345);
	}
	
	@RequestMapping("/demo2")
	public String test2(){
		System.out.println("demo2");
		System.out.println(new TestServiceImpl().getcount1());
		return "demo" ; 
	}
	
}



我在浏览器里面调用demo2的时候报错了,而且我实在找不到保存的信息了

下面是报错的信息

demo2
null
十二月 03, 2015 9:11:00 下午 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet [springmvc] in context with path [/appmanager] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at appmanager.service.impl.TestServiceImpl.getcount1(TestServiceImpl.java:18)
at appmanager.controller.Test.test2(Test.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2500)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2489)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

感觉TestDao bean 得不到值,问下大家我的配置是哪里错了


展开
收起
爱吃鱼的程序员 2020-06-10 10:18:42 770 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    你看你的异常信息,空指针异常, getcount1()-->  System.out.println(bean); bean是null, System.out.println(bean.getcount()); -->bean .getcount()空指针异常

    这个就是我主要想问的原因,按道理来说他应该去查询selectcount(1)fromdual返回的结果值吧

    你的dao上面没有加注解 

    @Repository

    publicinterfaceTestDao{

        publicintgetcount();回复 @minidai:同问我也报的一样的错误1111111111importorg.springframework.stereotype.Repository;@RepositorypublicinterfaceTestDao{publicintgetcount();}加了之后也是一样的效果,还是nullhttp://mybatis.org/spring/zh/sample.html上面那个是中文文档说明,并且该连接有官网实例,建议通过该实例进行学习。先将官网实例跑通,再自行搭建环境

    System.out.println(new TestServiceImpl().getcount1());

    这里new一个serviceImpl?? ????应该不能这样吧?


    回复 @minidai:解决就好看看我下面的评论,谢谢回复 @minidai:注入,跟serviceImpl引入dao应该一样的吧?那我应该怎么通过前台来调用这个service呢

    没仔细看,但是发现你吧xml放到了java的包里面,请移到resource里面,因为maven结构的java包只编译Java文件,其他都放到resource里面

    你好,我将XML文件移动到了resource下面的mybatis/mapper里面,然后配置文件里面写的是classpath:mybatis/mapper/*.xml,但是他却查找的是C:\Users\ADMINI~1\AppData\Local\Temp\0-appmanager\WEB-INF\classes\mybatis\mapper\TestDaoMapper.xml

    @Autowired
    TestServiceImplte ;
    @RequestMapping("/demo2")
    publicStringtest2(){

    System.out.println("demo2");
    System.out.println(te.getcount1());
    return"demo"; 

    }

    我修改为这样就可以调用了,,不过又出现一个问题

    我配置的mapper文件命名是classpath:appmanager/dao/impl/*.xml

    但是他去找的Theerrormayexistinfile[C:\Users\ADMINI~1\AppData\Local\Temp\0-appmanager\WEB-INF\classes\appmanager\dao\impl\TestDaoMapper.xml]

    这里我就不是很明白了,这是编译的问题还是我设置的问题呢。



    @minidai你eclipse里的server设置看过了么?回复 @杨延庆:还请你指教一下,在哪里看service设置输出目录回复 @minidai:那就要看你的项目了,你的server输出设定是不是放到Temp目录下了回复 @杨延庆:但是其他的spring配置文件也是这样写的,就是直接在项目下的classpath里面去找的,就是这个mapper文件不是你build的目录是WEB-INF,那当然classpath到这个目录下去找Mapper.xmlw文件

    谢谢各位,,我已经找到原因了,,最开始的问题是我使用service的时候使用方式错了,

    正确的调用应该是

    @AutowiredTestServiceImplte;@RequestMapping("/demo2")publicStringtest2(){System.out.println(te.getcount1());return"demo";}

    后来的查询mapper问题我把数据库的账号密码直接输入在配置文件之后就没出现了,现在已经全部链接通畅了,谢谢各位



    引用来自“alexgaoyh”的评论

    System.out.println(new TestServiceImpl().getcount1());

    这里new一个serviceImpl?? ????应该不能这样吧?


    引用来自“梦想沙漏”的评论

    没仔细看,但是发现你吧xml放到了java的包里面,请移到resource里面,因为maven结构的java包只编译Java文件,其他都放到resource里面

    恩,当时没仔细看,你new一个对象没有通过spring的容器管理,是无法完成自动注入的。不过你已经找到原因就ok了
    2020-06-10 10:19:01
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Java Spring Boot开发实战系列课程【第6讲】:Spring Boot 2.0实战MyBatis与优化(Java面试题) 立即下载
Spring框架入门 立即下载
陈曦:使用Spring.Initializr定制工程脚手架 立即下载

相关实验场景

更多