mybatis系列三:springMVC和mybatis的运用

来源:互联网 发布:淘宝客 群介绍 编辑:程序博客网 时间:2024/06/16 03:41

mybatis系列:

mybatis系列一:mybatis实现增删改查:

http://blog.csdn.net/wanlong360599336/article/details/71172060

mybatis系列二:Spring与MyBatis的整合实例:

http://blog.csdn.net/wanlong360599336/article/details/71194238


1.效果:


2.结构图:


3.看上面的结构图,重点的在于配置文件:


新建controller页面:

package com.mybatis.controller;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;import com.mybatis.interfaces.*;import com.mybatis.model.*;@Controller@RequestMapping("/article")public class UserController {@AutowiredIUserOperation userMapper;@RequestMapping("/list")public ModelAndView listall(HttpServletRequest request,HttpServletResponse response){List<Article> articles=userMapper.getUserArticles(24); ModelAndView mav=new ModelAndView("main");mav.addObject("articles",articles);return mav;}}



配置文件如下

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:aop="http://www.springframework.org/schema/aop"     xmlns:tx="http://www.springframework.org/schema/tx"     xmlns:context="http://www.springframework.org/schema/context"     xmlns:p="http://www.springframework.org/schema/p"     xsi:schemaLocation="              http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd              http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-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"              default-autowire="byName" default-lazy-init="false">       <!--本示例采用DBCP连接池,应预先把DBCP的jar包复制到工程的lib目录下。 -->   <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver"p:url="jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=utf8" p:username="root" p:password="password"p:maxActive="10" p:maxIdle="10"></bean><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  <property name="dataSource" ref="dataSource" /></bean>   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">      <!--dataSource属性指定要用到的连接池-->      <property name="dataSource" ref="dataSource"/>      <!--configLocation属性指定mybatis的核心配置文件-->      <property name="configLocation" value="classpath:config/Configuration.xml" />      <!-- 所有配置的mapper文件 -->     <property name="mapperLocations" value="classpath*:com/mybatis/mapper/*.xml" />  </bean>   <!-- MapperScannerConfigurer 去扫描所有的mapper接口 -->  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.mybatis.interfaces" />   </bean>    <!--   <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">          <property name="sqlSessionFactory" ref="sqlSessionFactory" />          <property name="mapperInterface" value="com.yihaomen.inter.IUserOperation" />   </bean>    --></beans> 

Configuration.xml:

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><!-- mybatis别名定义 --><typeAliases><typeAlias alias="User" type="com.mybatis.model.User" /><typeAlias alias="Article" type="com.mybatis.model.Article" /></typeAliases> <!-- 与spring 集成之后,这些可以完全删除,数据库连接的管理交给 spring 去管理 --><!-- <environments default="development"><environment id="development"><transactionManager type="JDBC" /><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis" /><property name="username" value="root" /><property name="password" value="password" /></dataSource></environment></environments> --><!-- 这里交给sqlSessionFactory 的 mapperLocations属性去得到所有配置信息 --><!-- <mappers><mapper resource="com/mybatis/mapper/User.xml" /></mappers> --></configuration><!-- Ctrl+Shift+F 自动排版 -->


mvc-dispatcher-servlet.xml:

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc" 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-3.0.xsd        http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-3.0.xsd        http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"><context:component-scan base-package="com.mybatis.controller" /><mvc:annotation-driven /><mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>      <mvc:default-servlet-handler/>       <beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix"><value>/WEB-INF/pages/</value></property><property name="suffix"><value>.jsp</value></property></bean></beans>


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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  <display-name>MyBatisStudys</display-name>  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list>  <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>  <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath*:config/applicationContext.xml</param-value><!-- 加载配置文件applicationContext.xml -->  </context-param>  <listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>  <listener>    <listener-class>org.springframework.web.context.ContextCleanupListener</listener-class>  </listener>  <servlet>    <servlet-name>mvc-dispatcher</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <load-on-startup>1</load-on-startup>  </servlet>  <servlet-mapping>    <servlet-name>mvc-dispatcher</servlet-name>  <!--这里的servlet-name的值要和 mvc-dispatcher-servlet.xml的名称一致 -->    <url-pattern>/</url-pattern>  </servlet-mapping> </web-app>

新建一个页面:

main.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><!-- "http://java.sun.com/jsp/jstl/core"需添加jstl.jar和standard.jar两个jar包,否则报错 --><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>article list</title></head><body><c:forEach items="${articles}" var="item">          ${item.id }--${item.title }--${item.content }<br /></c:forEach></body></html>

访问页面:

http://localhost:8080/MyBatisStudys/article/list



下载地址:   springMVC和Mybatis实例




在这里,springMVC配置的过程要注意一个细节,不然很容易报这种错误,例如 :  java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for ************

这次我就遇到了,原来是我的接口名和mapper里面的user.xml中定义的方法名称不一致导致的,所以要注意,网上有这种问题的几种解决方法:

按照步骤进行逐一检查:
1、mapper.xml中没有加入namespace 
2、mapper.xml中的方法和接口mapper的方法不对应 
3、mapper.xml没有加入到mybatis-config.xml中(即总的配置文件),例外:配置了mapper文件的包路径的除外 
4、mapper.xml文件名和所写的mapper名称不相同。


0 0
原创粉丝点击