spring MVC(十)---spring MVC整合mybatis

spring mvc可以通过整合hibernate来实现与数据库的数据交互,也可以通过mybatis来实现,这篇文章是总结一下怎么在springmvc中整合mybatis.

首先mybatis需要用到的包如图所示:


下面是mybaits的配置文件,写的地方由你决定,在这里我写在mybatis-servlet.xml中,因为我在web.xml中设置了在tomcat启动时会加载所有以servlet.xml结尾的文件。

web.xml中的部分代码(涉及到数据源的东西,在你的基础上加上就行),详细的请查看我spring mvc系列文章的前几篇:


  
 <!-- 
  引用该数据源
   -->
  <resource-ref>
  <span style="white-space:pre">	</span><res-ref-name>jndi_mysql</res-ref-name>
  <span style="white-space:pre">	</span><res-type>javax.sql.DataSource</res-type>
  </resource-ref>
	
mybatis-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.2.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
	
	
	
	<!--
	配置mybatis 
        在ioc容器中配置sqlSessionFactory
        使用SqlSessionFactoryBean工厂bean
            1 配置数据源
            2 配置映射文件  
                注意classpath前缀
                每在工程中添加一个映射文件,需要在list中添加一个value元素
     -->
     <bean id="ssf" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="ds"></property>
        <property name="mapperLocations">
            <list>
                <value>classpath:<span style="color:#ff0000;">com/etock/dao/MemberDaoIf-mapper.xml</span></value>
            </list>
        </property>
     </bean>
      <!-- 
     	DataSource 
     		1 实现类 DriverManageDataSource
     		2 JNDI方式
     			
      -->
     
                   <!--   第一种方式: -->
     <bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <span style="color:#ff0000;"><property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/cn"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property></span>
     </bean> 
     <!-- 第二种方式: -->
     <!-- <bean id="ds" class="org.springframework.jndi.JndiObjectFactoryBean">
     	<property name="jndiName" value="java:comp/env/com.mysql.jdbc.Driver"></property>
     </bean> -->
     <!-- 
        配置接口对应的实例bean对象
        spring中为了配置接口实例,提供 MapperFactoryBean的工厂bean
      -->
      <bean id="dao" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="sqlSessionFactory" ref="ssf"></property>
        <property name="mapperInterface" value="<span style="color:#ff0000;">com.etock.dao.MemberDaoIf"</span>></property>        
      </bean>
      <!-- 
        每在工程中添加一个接口,就需要在ioc容器中添加单独的bean节点使用mapperInterface实例化改接口
       -->
	
</beans>








使用时先建立一个bean类 如Member:

package com.etock.bean;

public class Member {
	private Integer currentPage;
	private Integer pageSize;
	
    private String name;
    private String email;
    private String password;
    private String autograph;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	
    public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getAutograph() {
		return autograph;
	}
	public void setAutograph(String autograph) {
		this.autograph = autograph;
	}
	public Integer getCurrentPage() {
		return currentPage;
	}
	public void setCurrentPage(Integer currentPage) {
		this.currentPage = currentPage;
	}
	public Integer getPageSize() {
		return pageSize;
	}
	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}

}
在定义dao层的接口:

package com.etock.dao;

import java.util.List;
import java.util.Map;

import com.etock.bean.Member;

public interface MemberDaoIf {
   public List<Member> <span style="color:#ff0000;">selectMembersByPage</span>(Map map);
   public int <span style="color:#ff0000;">selectMemberCount</span>();
}
然后是映射文件MemberDaoIf-mapper.xml:

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 
<mapper <span style="color:#ff0000;">namespace="com.etock.dao.MemberDaoIf" </span>>
   
 
   <!-- 
        这里返回的是list,但list里面存放的还是member对象,所以还是member
     -->

    <select id="<span style="color:#ff0000;">selectMemberCount</span>" resultType="java.lang.Integer">
        select count(*) from member;
    </select>
    <select id="<span style="color:#ff0000;">selectMembersByPage</span>" parameterType="java.util.Map" resultMap="<span style="color:#ff0000;">member</span>">
        select * from member limit #{start},#{max};
    </select>   


    <!-- 
        返回类型解释
     -->
    <resultMap type="com.etock.bean.Member" id="<span style="color:#ff0000;">member</span>">
        <result property="name" column="name"/>
        <result property="email" column="email"/>
        <result property="password" column="password"/>
        <result property="autograph" column="autograph"/>
    </resultMap>
</mapper>
然后是controller层

package com.etock.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.etock.bean.Member;
import com.etock.dao.MemberDaoIf;

@Controller
public class MemberController {
     
	<span style="color:#ff0000;">@Autowired
	private MemberDaoIf memberDao;</span>
	
	@RequestMapping("/selectMembersByPage")
	@ResponseBody
	public Map selectMembersByPage(Member member){
    	 
		Integer currentPage = member.getCurrentPage();
		Integer pageSize = member.getPageSize();
		
		<span style="color:#ff0000;">int totalCount = memberDao.selectMemberCount();</span>
		int totalPage = (totalCount+pageSize-1)/pageSize;
		<span style="color:#ff0000;">Map map = new HashMap();
        map.put("start", (currentPage-1)*pageSize);
		map.put("max", pageSize);</span>
       <span style="color:#ff0000;"> List<Member> list = memberDao.selectMembersByPage(map); </span>
        System.out.println(list.size()+"|||"+totalCount);
        /**
         * responseBody 将返回值封装成json返回给客户端
         */
        Map json = new HashMap();
        json.put("list",list);
        json.put("totalCount", totalCount);
        json.put("totalPage", totalPage);
        
		
		return json;
     }
}
下面是我项目文件的结构图:











版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-09-01 14:20  dingxiaoyue  阅读(215)  评论(0编辑  收藏  举报