14、mybatis与spring、springmvc集成

在这一系列文章中,前面讲到纯粹用mybatis 连接数据库,然后 进行增删改查,以及多表联合查询的的例子,但实际项目中,通常会用 spring 这个沾合剂来管理 datasource 等。充分利用spring 基于接口的编程,以及aop ,ioc 带来的方便。用spring 来管理 mybatis 与管理hibernate 有很多类似的地方。今天的重点就是数据源管理以及 bean的配置。

1、先加载一些spring相关的jar文件(附件springBlank),在执行过程中报classnotfound时,再网上下载
14、mybatis与spring、springmvc集成_第1张图片

2、首先对前面的工程结构做一点改变,在src_user源代码目录下建立文件夹config ,并将原来的 mybatis 配置文件 Configuration.xml 移动到这个文件夹中, 并在config 文家夹中建立 spring 配置文件:applicationContext.xml ,这个配置文件里最主要的配置:

14、mybatis与spring、springmvc集成_第2张图片

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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd" xmlns:tx="http://www.springframework.org/schema/tx">

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"/> 
		<property name="url" value="jdbc:mysql://127.0.0.1:3306/abcc?characterEncoding=utf8"/>
		<property name="username" value="root"></property>
		<property name="password" value="111122"></property>
	</bean>
	
	 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 
	 	  <property name="dataSource" ref="dataSource"/> 
	 	  <property name="configLocation" value="config/Configuration.xml"/> 
	 </bean>
	
	<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
		 <property name="sqlSessionFactory" ref="sqlSessionFactory" /> 
		 <property name="mapperInterface" value="com.yihaomen.mybatis.inter.IUserOperation" />
	 </bean>
</beans>

 这里面的重点就是 org.mybatis.spring.SqlSessionFactoryBean 与 org.mybatis.spring.mapper.MapperFactoryBean[b] 实现了 spring  的接口,并产生对象。

没有对Configuration.xml修改;

 

创建测试类MybatisSprintTest :

package com.yihaomen.test;

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.yihaomen.mybatis.inter.IUserOperation;
import com.yihaomen.mybatis.model.Article;
import com.yihaomen.mybatis.model.User;
public class MybatisSprintTest {
    private static ApplicationContext ctx;  
    static 
    {  
        ctx = new ClassPathXmlApplicationContext("config/applicationContext.xml"); 
    }        
    public static void main(String[] args)  
    {  
        IUserOperation mapper = (IUserOperation)ctx.getBean("userMapper");   //查找id="userMapper"的类
        User user = mapper.selectUserByID(1);  //调用User.xml文件配置id="selectUserByID"的方法
        System.out.println(user.getUserAddress()); 
        List<Article> articles = mapper.getUserArticles(1); //调用User.xml文件配置id="getUserArticles"的方法
        for(Article article:articles){
            System.out.println(article.getContent()+"--"+article.getTitle());
        }
    }  
}

 报错:Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory

下载:http://mvnrepository.com/     commons-logging-1.1.1.jar

报错:java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource

下载:commons-dbcp-1.4.jar

报错:java.lang.ClassNotFoundException: org.apache.commons.pool.ObjectPool

下载:commons-pool-1.6.jar

报错:java.lang.ClassNotFoundException: org.mybatis.spring.SqlSessionFactoryBean

下载:mybatis-spring-1.1.1.jar

报错:java.lang.ClassNotFoundException: org.springframework.dao.support.DaoSupport

下载:spring-tx-4.0.6.RELEASE.jar

好,现在没有报错了;输出结果。

表明spring的集成成功,接管了mybatis的配置文件

 

 

若对springMVC还不是很懂的朋友,请先看后面的一章springMVC+spring+hibernate;下面开始整合springmvc+spring+mybatis

1、添加jar文件这里就不再一个一个的下载了,有兴趣的朋友可以自己比较下:项目springmvcMb附录下载

14、mybatis与spring、springmvc集成_第3张图片

2.web.xml

出现:The content of element type "web-app" must match "时表明4个标签顺序不对,<context> <filter> <listener> <servlet> 

 

<?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>springmvcMb</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
<filter>  
    <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>  
    <url-pattern>/*</url-pattern>  
</filter-mapping>
  
  
<servlet>  
    <servlet-name>dispatcherServlet</servlet-name>  
    <servlet-class>  
        org.springframework.web.servlet.DispatcherServlet  
    </servlet-class>  
    <init-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath*:config/web-servlet.xml,classpath*:config/dao-servlet.xml</param-value>  
    </init-param>  
    <load-on-startup>1</load-on-startup>  
</servlet>  
<servlet-mapping>  
    <servlet-name>dispatcherServlet</servlet-name>  
    <url-pattern>/</url-pattern>  
</servlet-mapping>  
 
</web-app>

 2.1、web-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.yihaomen.controller" />
	<mvc:annotation-driven />
	
	<mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>  
    <mvc:default-servlet-handler/>  
     
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/WEB-INF/pages/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>
</beans>

 2.2、dao-servlet.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目录下。 -->   
    <context:property-placeholder	location="classpath:/config/database.properties" />
		
	<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/abcc?characterEncoding=utf8" 
		p:username="root" p:password="111122"
		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/yihaomen/mapper/*.xml" />
  </bean> 
  
  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	 <property name="basePackage" value="com.yihaomen.inter" />	 
  </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> 

 2.2.1  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>
    <typeAliases> 
        <typeAlias alias="User" type="com.yihaomen.model.User"/>
        <typeAlias alias="Article" type="com.yihaomen.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?characterEncoding=utf8" />
			<property name="username" value="root"/>
			<property name="password" value="password"/>
			</dataSource>
		</environment>
	</environments>
	-->
	
	<!-- 这里交给sqlSessionFactory 的 mapperLocations属性去得到所有配置信息 -->
	<!-- 
	<mappers>
	    <mapper resource="com/yihaomen/mapper/User.xml"/>
	</mappers>
	--> 	
</configuration>

2.2.2 src/com/yihaomen/mapper/User.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="com.yihaomen.inter.IUserOperation">

	<select id="selectUserByID" parameterType="int" resultType="User">
	    select * from `user` where id = #{id}
	</select>
	
	<!-- 为了返回list 类型而定义的returnMap -->
	<resultMap type="User" id="resultListUser">
        <id column="id" property="id" />
        <result column="userName" property="userName" />
        <result column="userAge" property="userAge" />
        <result column="userAddress" property="userAddress" />
       </resultMap>
	
	<!-- 返回list 的select 语句,注意 resultMap 的值是指向前面定义好的 -->
	<select id="selectUsers" parameterType="string" resultMap="resultListUser">
	    select * from user where userName like #{userName}
	</select>
				
	<resultMap id="resultUserArticleList" type="Article">
	    <id property="id" column="aid" />
	    <result property="title" column="title" />
	    <result property="content" column="content" />	    
	    <association property="user" javaType="User" resultMap="resultListUser" />	         
	</resultMap>
	
	<select id="getUserArticles" parameterType="int" resultMap="resultUserArticleList">
	   select user.id,user.userName,user.userAddress,article.id aid,article.title,article.content from user,article 
	          where user.id=article.userid and user.id=#{id}
	</select>
	
    <insert id="addUser" parameterType="User" 
        useGeneratedKeys="true" keyProperty="id"> 
        insert into user(userName,userAge,userAddress)  
             values(#{userName},#{userAge},#{userAddress})  
    </insert>
    
    <update id="updateUser" parameterType="User" >
        update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id}
    </update>
    
    <delete id="deleteUser" parameterType="int">
        delete from user where id=#{id}
    </delete>
    
</mapper>

2.2.3 src/config/database.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/abcc?characterEncoding=utf8
jdbc.username=root
jdbc.password=111122

3、model类,操作接口、前端显示;

package com.yihaomen.model;
public class User {	
	private int id;
	private String userName;
	private String userAge;
	private String userAddress;


package com.yihaomen.model;
public class Article {	
	private int id;
	private User user;
	private String title;
	private String content;

package com.yihaomen.inter;
import java.util.List;
public interface IUserOperation {   
	public User selectUserByID(int id);
	public List<User> selectUsers(String userName);	
	public void addUser(User user);
	public void updateUser(User user);
	public void deleteUser(int id);	
	public List<Article> getUserArticles(int id);

package com.yihaomen.controller;
@Controller
public class UserController {
	@Autowired
	IUserOperation userMapper;
	@RequestMapping("/list")
	public ModelAndView listall(HttpServletRequest request,HttpServletResponse response){
		List<Article> articles=userMapper.getUserArticles(1); 
		return new ModelAndView("/list","articles",articles);

 测试:http://localhost:9080/springmvcMb/list

集成完成!

 

开发过程中可能遇到的问题:

 *@RequestMapping

下载:spring-web-4.1.0.RELEASE.jar

*ModelAndView

下载:spring-webmvc-4.1.0.RELEASE.jar

*HttpServletRequest    表示缺少servlet-api.jar的包

添加tomcat库:右键属性--  java build  path--add libaray 

添加:jstl标签库  

下载;jstl-1.2.jar

在需要用到jstl表达式的jsp上加上:<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 

 

mybatis设置分页显示:

mybatis动态sql语句查询 将在后面的高级运用中讲解

本章内容结束,欢迎来群:366437263

 

你可能感兴趣的:(springMVC)