MyBatis从入门到精通(第9章):Spring集成MyBatis(下)

springmvc执行流程原理

  • mybatis-spring  可以帮助我们将MyBatis代码无缝整合到Spring中。使用这个类库中的类,Spring将会加载必要的MyBatis工厂类和Session类。
  • MyBatis Spring Adapter项目地址为:  https://github.com/mybatis/spring
    <dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.3</version>
</dependency>

9.4.3 开发业务层(Service层)

虽然针对接口编程对小的项目来说并不重要,但是这里为了形式上的需要仍然提供了Service接口。

在 src/main/java 中新建 cn.bjut.mybatis.web.service 包,然后添加 DictService接口,代码如下。

package cn.bjut.mybatis.web.service;

import cn.bjut.mybatis.web.model.SysDict;

import java.util.List;

/**
* @author kangmianfeng
*/
public interface DictService { SysDict findById(Long id); List<SysDict> findBySysDict(SysDict sysDict, Integer offset, Integer limit); boolean saveOrUpdate(SysDict sysDict); boolean deleteById(Long id);
}

Service层的 saveOrUpdate 方法对应DAO层的 Mapper 中的insert和updateById方法,其他3个方法和DAO层的方法一 一对应。

在 cn.bjut.mybatis.web.service 包下创建 impl包,然后新建 DictService接口的实现类 DictServiceImpl,代码如下。

package cn.bjut.mybatis.web.service.Impl;

import cn.bjut.mybatis.web.mapper.DictMapper;
import cn.bjut.mybatis.web.model.SysDict;
import cn.bjut.mybatis.web.service.DictService;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.List; /**
* @author kangmianfeng
*/
@Service
public class DictServiceImpl implements DictService { @Autowired
private DictMapper dictMapper; @Override
public SysDict findById(Long id) {
return dictMapper.selectByPrimaryKey(id);
} public List<SysDict> findBySysDict(SysDict sysDict, Integer offset, Integer limit) {
RowBounds rowBounds = RowBounds.DEFAULT;
if(offset != null && limit != null){
rowBounds = new RowBounds(offset, limit);
}
return dictMapper.selectBySysDict(sysDict, rowBounds);
} @Override
public boolean saveOrUpdate(SysDict sysDict) {
if(sysDict.getId() == null){
return dictMapper.insert(sysDict) == 1;
} else {
return dictMapper.updateById(sysDict) == 1;
}
} @Override
public boolean deleteById(Long id) {
if(id == null){
throw new NullPointerException("id");
}
return dictMapper.deleteById(id) == 1;
}
}

Service的实现类中需要添加 @Service注解,在9.2节集成Spring时配置过“自动扫描包”,包名是 cn.bjut.mybatis.web.service.impl ,

DictServiceImpl实现类所在的包就是符合这个包名规则的,加上注解后,Spring在初始化时就会扫描到这个类,然后由Spring管理这个类。

因为配置了自动扫描Mapper接口,所以在 Service层 可以直接通过以下代码 注入Mapper 。

@Autowired

private DictMapper dictMapper;

9.4.4 开发控制层(Controller层)

在 cn.bjut.mybatis.web.controller 包下,新建 DictController类,代码如下。

package cn.bjut.mybatis.web.controller;

import cn.bjut.mybatis.web.model.SysDict;
import cn.bjut.mybatis.web.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView; import java.util.List; /**
* @author kangmianfeng
*/
@Controller
@RequestMapping("/dicts")
public class DictController { @Autowired
private DictService dictService; /**
* 显示字典数据列表
*
* @param sysDict
* @param offset
* @param limit
* @return
*/
@RequestMapping
public ModelAndView dicts(SysDict sysDict, Integer offset, Integer limit) {
ModelAndView mv = new ModelAndView("dicts");
List<SysDict> dicts = dictService.findBySysDict(sysDict, offset, limit);
mv.addObject("dicts", dicts);
return mv;
} /**
* 新增或修改字典信息页面,使用 get 跳转到页面
*
* @param id
* @return
*/
@RequestMapping(value = "add", method = RequestMethod.GET)
public ModelAndView add(Long id) {
ModelAndView mv = new ModelAndView("dict_add");
SysDict sysDict;
if(id == null){
//如果 id 不存在,就是新增数据,创建一个空对象即可
sysDict = new SysDict();
} else {
//如果 id 存在,就是修改数据,把原有的数据查询出来
sysDict = dictService.findById(id);
}
mv.addObject("model", sysDict);
return mv;
} /**
* 新增或修改字典信息,通过表单 post 提交数据
*
* @param sysDict
* @return
*/
@RequestMapping(value = "add", method = RequestMethod.POST)
public ModelAndView save(SysDict sysDict) {
ModelAndView mv = new ModelAndView();
try {
dictService.saveOrUpdate(sysDict);
mv.setViewName("redirect:/dicts");
} catch (Exception e){
mv.setViewName("dict_add");
mv.addObject("msg", e.getMessage());
mv.addObject("model", sysDict);
}
return mv;
} /**
* 通过 id 删除字典信息
*
* @param id
* @return
*/
@RequestMapping(value = "delete", method = RequestMethod.POST)
@ResponseBody
public ModelMap delete(@RequestParam Long id) {
ModelMap modelMap = new ModelMap();
try {
boolean success = dictService.deleteById(id);
modelMap.put("success", success);
} catch (Exception e) {
modelMap.put("success", false);
modelMap.put("msg", e.getMessage());
}
return modelMap;
} }

上面这段代码中使用了两个视图,分别为dicts和dict_add。在下一节中,我们将继续编写视图层代码。

9.4.5 开发视图层(View层)

按照9.2节中的视图配置,需要在 src/main/webapp下面的WEB-INF中 创建jsp目录,然后在jsp中创建 dicts.jsp和dict_add.jsp ,

dicts.jsp代码如下。

<%@ page language="java" contentType="text/html; charset=UTF8" pageEncoding="UTF8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<c:set var="path" value="${pageContext.request.contextPath}"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF8">
<title>字典信息</title>
<script src="${path}/static/jquery-3.1.1.min.js"></script>
</head>
<body>
<table>
<tr>
<th colspan="4">字典管理</th>
</tr>
<tr>
<th>类别名</th>
<th>字典名</th>
<th>字典值</th>
<th> 操作 [<a href="${path}/dicts/add">新增</a>]</th>
</tr>
<c:forEach items="${dicts}" var="dict">
<tr id="dict-${dict.id}">
<td>${dict.code}</td>
<td>${dict.name}</td>
<td>${dict.value}</td>
<td>
[<a href="${path}/dicts/add?id=${dict.id}">编辑</a>]
[<a href="javascript:;" onclick="deleteById(${dict.id}, '${dict.name}')">删除</a>]
</td>
</tr>
</c:forEach>
</table>
<script>
function deleteById(id, label){
var r = confirm('您确定要删除“' + label + '”吗?');
if(r){
$.ajax({
url: '${path}/dicts/delete',
data: {
id: id
},
dataType: 'json',
type: 'POST',
success: function(data){
if(data.success){
$('#dict-' + id).remove();
} else {
alert(data.msg);
}
}
})
}
}
</script>
</body>
</html>

dict_add.jsp代码如下。

<%@ page language="java" contentType="text/html; charset=UTF8" pageEncoding="UTF8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<c:set var="path" value="${pageContext.request.contextPath}"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF8">
<title>字典维护</title>
</head>
<body>
<form action="${path}/dicts/add" method="post">
<input type="hidden" name="id" value="${model.id}">
<table>
<c:if test="${msg != null}">
<tr>
<th colspan="2" style="color:red;max-width:400px;">${msg}</th>
</tr>
</c:if>
<tr>
<th colspan="2">字典维护</th>
</tr>
<tr>
<th>类别名</th>
<td><input type="text" name="code" value="${model.code}"></td>
</tr>
<tr>
<th>字典名</th>
<td><input type="text" name="name" value="${model.name}"></td>
</tr>
<tr>
<th>字典值</th>
<td><input type="text" name="value" value="${model.value}"></td>
</tr>
<tr>
<th colspan="2">
<input type="submit" value="保存">
<input type="button" onclick="backToList()" value="取消">
</th>
</tr>
</table>
</form>
<script>
function backToList(){
location.href = '${path}/dicts';
}
</script>
</body>
</html>

dicts.jsp  代码中使用了  jquery-3.1.1.min.js  ,大家可以从地址  https://code.jquery.com/jquery-3.1.1.min.js  中下载jQuery, 然后放在 webapp/static/ 目录里面。

9.4.6 部署和运行应用

将项目部署到Tomcat下,然后启动服务。服务器启动完成后,在浏览器中输入  http://localhost:8080/mybatis-spring/dicts  并访问,

简单的字典管理操作界面便实现了。

熟练掌握基础功能开发后,结合前面几章学习的MyBatis的各种技巧后,我们就能实现各种各样的功能了。

注意:由于我们使用的是代理 Dao 的模式,Dao 具体实现类由 MyBatis 使用动态代理方式创建,所以此时mybatis 配置文件不能删。

当我们整合 spring 和 mybatis 时,mybatis 创建的 Mapper.xml 文件名必须和 Dao接口 文件名一致 。

====================

end

MyBatis从入门到精通(第9章):Spring集成MyBatis(下)的更多相关文章

  1. MyBatis从入门到精通(第5章):5.4 Example 介绍

    jdk1.8.MyBatis3.4.6.MySQL数据库5.6.45.Eclipse Version: 2019-12 M2 (4.14.0) MyBatis从入门到精通(第5章):MyBatis代码 ...

  2. MyBatis从入门到精通(第9章):Spring集成MyBatis(中)

    MyBatis从入门到精通(第9章):Spring集成MyBatis(中) 框架(Framework)是整个或部分系统的可重用设计,表现为一组抽象构件及构件实例间交互的方法.应该将应用自身的设计和具体 ...

  3. MyBatis从入门到精通(第9章):Spring集成MyBatis(上)

    MyBatis从入门到精通(第9章):Spring集成MyBatis(上) Spring是一个为了解决企业级Web应用开发过程中面临的复杂性,而被创建的一个非常流行的轻量级框架. mybatis-sp ...

  4. MyBatis从入门到精通(第5章):MyBatis代码生成器

    jdk1.8.MyBatis3.4.6.MySQL数据库5.6.45.Eclipse Version: 2019-12 M2 (4.14.0) MyBatis从入门到精通(第5章):MyBatis代码 ...

  5. MyBatis从入门到精通(第6章):MyBatis 高级查询->6.1.1高级结果映射之一对一映射

    jdk1.8.MyBatis3.4.6.MySQL数据库5.6.45.IntelliJ IDEA 2019.2.4 本章主要包含的内容为 MyBatis 的高级结果映射,主要处理数据库一对一.一对多的 ...

  6. MyBatis从入门到精通(第3章):MyBatis注解方式的基本使用

    MyBatis 注解方式就是将 SQL 语句直接写在DAO层的接口上. 在黑马录制的2018年双元视频课:\08 SSM整合案例[企业权限管理系统]\07.订单操作  有使用MyBatis注解进行多表 ...

  7. MyBatis从入门到精通(第6章):MyBatis 高级查询->6.1.2高级结果映射之一对多映射

    jdk1.8.MyBatis3.4.6.MySQL数据库5.6.45.IntelliJ IDEA 2019.3.1 本章主要包含的内容为 MyBatis 的高级结果映射,主要处理数据库一对一.一对多的 ...

  8. MyBatis从入门到精通(第4章):MyBatis动态SQL【foreach、bind、OGNL用法】

    (第4章):MyBatis动态SQL[foreach.bind.OGNL用法] 4.4 foreach 用法 SQL 语句中有时会使用 IN 关键字,例如 id in (1,2,3).可以使用 ${i ...

  9. MyBatis从入门到精通(第4章):MyBatis动态SQL【if、choose 和 where、set、trim】

    (第4章):MyBatis动态SQL[if.choose 和 where.set.trim] MyBatis 的强大特性之一便是它的动态 SQL.MyBatis 3.4.6版本采用了功能强大的OGNL ...

随机推荐

  1. React 学习笔记(1) 基础语法和生命周期

    参看:视频地址 简单搭建一个react-cli: 2. React.createElement() 将object转化为 React语法 import React from 'react' impor ...

  2. 深度解析Critical Thinking的四个阶段

    关于批判性思维我们一直都在讨论学习,但是小编相信没有几个留学生敢说自己有Critical Thinking,但它又是essay写作中必须存在的.那么批判性思维需要怎么培养呢?今天小编就给同学们分析一下 ...

  3. Bean 注解(Annotation)配置(3)- 依赖注入配置

    Spring 系列教程 Spring 框架介绍 Spring 框架模块 Spring开发环境搭建(Eclipse) 创建一个简单的Spring应用 Spring 控制反转容器(Inversion of ...

  4. HDU - 4405 Aeroplane chess(期望dp)

    题意:沿着x轴从0走到大于等于N的某处,每一步的步数由骰子(1,2,3,4,5,6)决定,若恰好走到x轴上某飞行路线的起点,则不计入扔骰子数.问从0走到大于等于N的某处的期望的扔骰子次数. 分析: 1 ...

  5. POJ 1276:Cash Machine 多重背包

    Cash Machine Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 30006   Accepted: 10811 De ...

  6. 原生js完成打地鼠小游戏

    :这是首页,有简单模式和地狱模式两种模式进行选择 这是选择完模式之后的游戏界面:30秒一局游戏倒计时,每打中一只老鼠加一分,没砸中减一分,没砸不加不减 首先准备几张图片 html代码: <!-- ...

  7. gdal库的学习和使用

    1.windows下的编译 1.1.解压后打开nmake.opt,设置GDAL_HOME 1.2.进入vs的command promot,进入正常的那个即可,64位的没试过,可以参考gdal官网 1. ...

  8. 10几行代码,用python打造实时截图识别OCR

    你一定用过那种“OCR神器”,可以把图片中的文字提取出来,极大的提高工作效率. !   今天,我们就来做一款实时截图识别的小工具.顾名思义,运行程序时,可以实时的把你截出来的图片中的文字识别出来. 下 ...

  9. 吴裕雄--天生自然TensorFlow2教程:数据统计

    import tensorflow as tf a = tf.ones([2, 2]) a tf.norm(a) tf.sqrt(tf.reduce_sum(tf.square(a))) a = tf ...

  10. 《Thinking in Java》中讲到了final,发现自己有部分地方迷糊

    1.1当给全局的静态字段加上final时,系统是不会给其赋默认值的,若不手动初始化,会编译时错误——Variable 'xxx' might not have been initialized. 1. ...