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

下面是我项目文件的结构图:

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

spring MVC(十)---spring MVC整合mybatis的更多相关文章

  1. Spring Boot入门系列(十八)整合mybatis,使用注解的方式实现增删改查

    之前介绍了Spring Boot 整合mybatis 使用xml配置的方式实现增删改查,还介绍了自定义mapper 实现复杂多表关联查询.虽然目前 mybatis 使用xml 配置的方式 已经极大减轻 ...

  2. Spring Boot入门系列(十九)整合mybatis,使用注解实现动态Sql、参数传递等常用操作!

    前面介绍了Spring Boot 整合mybatis 使用注解的方式实现数据库操作,介绍了如何自动生成注解版的mapper 和pojo类. 接下来介绍使用mybatis 常用注解以及如何传参数等数据库 ...

  3. Spring Boot2 系列教程 (十三) | 整合 MyBatis (XML 版)

    前言 如题,今天介绍 SpringBoot 与 Mybatis 的整合以及 Mybatis 的使用,之前介绍过了 SpringBoot 整合MyBatis 注解版的使用,上一篇介绍过 MyBatis ...

  4. Spring (六):整合Mybatis

    本文是按照狂神说的教学视频学习的笔记,强力推荐,教学深入浅出一遍就懂!b站搜索狂神说或点击下面链接 https://space.bilibili.com/95256449?spm_id_from=33 ...

  5. spring boot(二)整合mybatis plus+ 分页插件 + 代码生成

    先创建spring boot项目,不知道怎么创建项目的 可以看我上一篇文章 用到的环境 JDK8 .maven.lombok.mysql 5.7 swagger 是为了方便接口测试 一.Spring ...

  6. Java开发学习(三十九)----SpringBoot整合mybatis

    一.回顾Spring整合Mybatis Spring 整合 Mybatis 需要定义很多配置类 SpringConfig 配置类 导入 JdbcConfig 配置类 导入 MybatisConfig ...

  7. Spring Boot 知识笔记(整合Mybatis)

    一.pom.xml中添加相关依赖 <!-- 引入starter--> <dependency> <groupId>org.mybatis.spring.boot&l ...

  8. Spring入门(四)——整合Mybatis

    1. 准备jar包及目录结构 2. 配置db.properties driver = com.mysql.jdbc.Driver url = jdbc:mysql://127.0.0.1:3306/H ...

  9. Spring Boot数据访问之整合Mybatis

    在Mybatis整合Spring - 池塘里洗澡的鸭子 - 博客园 (cnblogs.com)中谈到了Spring和Mybatis整合需要整合的点在哪些方面,需要将Mybatis中数据库连接池等相关对 ...

随机推荐

  1. Order Management Suite - Pricing and Availability Form Library

    In this Document   Purpose   Scope   Details   A. Form / Functional Issues   "Add to Selection& ...

  2. ThreadPoolExecutor运行机制

    最近发现几起对ThreadPoolExecutor的误用,其中包括自己,发现都是因为没有仔细看注释和内部运转机制,想当然的揣测参数导致,先看一下新建一个ThreadPoolExecutor的构建参数: ...

  3. Android的Context Manager(服务管理器)源码剖析-android学习之旅(99)

    Context Manager介绍 Context Manager对应的进程是servicemanager进程,它先于Service Server和服务客户端运行,进入接收IPC数据的待机状态,处理来 ...

  4. C++语言之析构函数与构造函数

    #include <iostream> using namespace std ; class Dog { //默认情况下定义变量为私有 int a ; public: //两个函数都只能 ...

  5. jsp标签jsp:setProperty用法

    <jsp:setProperty>用来设置已经实例化的Bean对象的属性 第一种形式: <jps:setProperty name = "JavaBean实例名" ...

  6. 如何oracle调试存储过程

    1.打开PL/SQL Developer 如果在机器上安装了PL/SQL Developer的话,打开PL/SQL Developer界面 输入用户名,密码和host名字,这个跟在程序中web.con ...

  7. 恶补web之一:html学习(2)

    iframe用于在网页内显示网页:<iframe src="URL"></iframe>,iframe可用作链接的目标: <!DOCTYPE html ...

  8. Django处理流程

    用户通过浏览器发送请求 请求到达request中间件,中间件对request请求做预处理或者直接返回response 若未返回response,会到达urlconf路由,找到对应视图函数 视图函数做相 ...

  9. <mate name="viewport">移动端设置详解

    <meta name="viewport" content="width=device-width,height=device-height,initial-sca ...

  10. JAVA程序员面试宝典

    程序员面试之葵花宝典 面向对象的特征有哪些方面    1. 抽象:抽象就是忽略一个主题中与当前目标2. 无关的那些方面,3. 以便更充分地注意与当前目标4. 有关的方面.抽象并不5. 打算了解全部问题 ...