通常情况下,我们之间调用mapper,spring会为我们注入其实现,很方便,mybatis也提供了一个generator供我们生成bean、dao接口等。但是总有一种感觉叫不爽,感觉除了bean和mapping.xml之外,dao接口有着共性,没有必要每一个都写一遍,共性的东东要提出来。下面就说一下怎么利用面向接口的思想进行提炼!

1、bean接口IModel

package com.jdw.bean;

/**
* 所有的bean都要implements该接口
* 至于原因,且往后看!
* @author Administrator
*
*/
public interface IModel { }

2、实现IModel接口的Category

package com.jdw.bean;
/**
* 实现了IModel接口的Category Bean
* @author Administrator
*
*/
public class Category implements IModel { private Integer cId; private String cName; private Boolean hot; public Integer getCId() {
return cId;
} public void setCId(Integer cId) {
this.cId = cId;
} public String getCName() {
return cName;
} public void setCName(String cName) {
this.cName = cName == null ? null : cName.trim();
} public Boolean getHot() {
return hot;
} public void setHot(Boolean hot) {
this.hot = hot;
} @Override
public String toString() {
return "Category [cId=" + cId + ", cName=" + cName + ", hot=" + hot + "]";
} }

3、dao接口的接口IMapper

package com.jdw.dao;

import com.jdw.bean.IModel;

/**
* mybatis mapper都要extends该接口
* @author Administrator
*
* @param <M>
*/
public interface IMapper<M extends IModel>{ int deleteByPrimaryKey(Integer id); int insert(M model); int insertSelective(M model); M selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(M model); int updateByPrimaryKey(M model);
}

4、继承了IMapper接口的Category接口

package com.jdw.dao;

import java.util.List;
import java.util.Map; import org.apache.ibatis.annotations.Param; import com.jdw.bean.Category; /**
* 继承了IMapper接口的CategoryMapper接口
* 可以看出,现在只需要在这里面写特有的接口了,共性的接口放到IMapper里面了
* @author Administrator
*
*/
public interface CategoryMapper extends IMapper<Category> {
public List<Category> selectCategoryByType(@Param("type") String type); public void deleteByIds(String ids); public List<Category> selectCategoryByPage(Map<String, Object> map);
}

5、CategoryMapping.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.jdw.dao.CategoryMapper">
<resultMap id="BaseResultMap" type="com.jdw.bean.Category">
<!-- WARNING - @mbggenerated This element is automatically generated by
MyBatis Generator, do not modify. -->
<id column="c_id" property="cId" jdbcType="INTEGER" />
<result column="c_name" property="cName" jdbcType="VARCHAR" />
<result column="hot" property="hot" jdbcType="BIT" />
</resultMap>
<sql id="Base_Column_List">
<!-- WARNING - @mbggenerated This element is automatically generated by
MyBatis Generator, do not modify. -->
c_id, c_name, hot
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap"
parameterType="java.lang.Integer">
<!-- WARNING - @mbggenerated This element is automatically generated by
MyBatis Generator, do not modify. -->
select
<include refid="Base_Column_List" />
from category
where c_id = #{cId,jdbcType=INTEGER}
</select>
<select id="selectCategoryByType" resultMap="BaseResultMap"
parameterType="java.lang.String">
<!-- WARNING - @mbggenerated This element is automatically generated by
MyBatis Generator, do not modify. -->
select
<include refid="Base_Column_List" />
from category
where 1 = 1
<if test="type != null and type !=''">
AND c_name = #{type,jdbcType=VARCHAR}
</if>
ORDER BY c_id
</select>
<select id="selectCategoryByPage" resultMap="BaseResultMap"
parameterType="java.util.Map"> select
<include refid="Base_Column_List" />
from category
where 1 = 1
<if test="type != null and type !=''">
AND c_name = #{type,jdbcType=VARCHAR}
</if>
ORDER BY c_id
limit #{pageIndex},#{pageSize}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
<!-- WARNING - @mbggenerated This element is automatically generated by
MyBatis Generator, do not modify. -->
delete from category
where c_id = #{cId,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.jdw.bean.Category">
<!-- WARNING - @mbggenerated This element is automatically generated by
MyBatis Generator, do not modify. -->
insert into category (c_id, c_name, hot)
values (#{cId,jdbcType=INTEGER}, #{cName,jdbcType=VARCHAR},
#{hot,jdbcType=BIT})
</insert>
<insert id="insertSelective" parameterType="com.jdw.bean.Category">
<!-- WARNING - @mbggenerated This element is automatically generated by
MyBatis Generator, do not modify. -->
insert into category
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="cId != null">
c_id,
</if>
<if test="cName != null">
c_name,
</if>
<if test="hot != null">
hot,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="cId != null">
#{cId,jdbcType=INTEGER},
</if>
<if test="cName != null">
#{cName,jdbcType=VARCHAR},
</if>
<if test="hot != null">
#{hot,jdbcType=BIT},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.jdw.bean.Category">
<!-- WARNING - @mbggenerated This element is automatically generated by
MyBatis Generator, do not modify. -->
update category
<set>
<if test="cName != null">
c_name = #{cName,jdbcType=VARCHAR},
</if>
<if test="hot != null">
hot = #{hot,jdbcType=BIT},
</if>
</set>
where c_id = #{cId,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.jdw.bean.Category">
<!-- WARNING - @mbggenerated This element is automatically generated by
MyBatis Generator, do not modify. -->
update category
set c_name = #{cName,jdbcType=VARCHAR},
hot = #{hot,jdbcType=BIT}
where c_id = #{cId,jdbcType=INTEGER}
</update>
</mapper>

6、来点猛料,实现IMapper接口的BaseDaoImpl,注意看其中的T,spring可以Autowired泛型T,这个很巧妙!

package com.jdw.dao.impl;

import org.springframework.beans.factory.annotation.Autowired;

import com.jdw.bean.IModel;
import com.jdw.dao.IMapper; /**
* 面向接口+泛型的威力初体验
*
* @author Administrator
*
* @param <T>
* @param <M>
*/
public class BaseDaoImpl<T extends IMapper<M>,M extends IModel> implements IMapper<M> { @Autowired
protected T t; @Override
public int deleteByPrimaryKey(Integer id) {
int result = this.t.deleteByPrimaryKey(id);
return result;
} @Override
public int insert(M model) {
int result = this.t.insert(model);
return result;
} @Override
public int insertSelective(M model) {
int result = this.t.insertSelective(model);
return result;
} @Override
public M selectByPrimaryKey(Integer id) {
M m=this.t.selectByPrimaryKey(id);
return m;
} @Override
public int updateByPrimaryKeySelective(M model) {
int result=this.t.updateByPrimaryKeySelective(model);
return result;
} @Override
public int updateByPrimaryKey(M model) {
int result=this.t.updateByPrimaryKey(model);
return result;
} }

7、继承了BaseDaoImpl的CategoryDaoImpl,注意少了很多共性代码,只有特性接口的实现,连spring mapper注入都省了!

package com.jdw.dao.impl;

import java.util.List;
import java.util.Map; import org.springframework.stereotype.Repository; import com.jdw.bean.Category;
import com.jdw.dao.CategoryMapper;
/**
* 继承了BaseDaoImpl的CategoryImpl
* 注意:
* (1)这里只需要实现特有的接口方法
* (2)注意这里的mybatis mapper是根据泛型从BaseDaoImpl继承而来的
* @author Administrator
*
*/
@Repository(value = "categoryDao")
public class CategoryDaoImpl extends BaseDaoImpl<CategoryMapper, Category> implements CategoryMapper { @Override
public List<Category> selectCategoryByType(String type) {
List<Category> list = this.t.selectCategoryByType(type);
return list;
} @Override
public void deleteByIds(String ids) { } @Override
public List<Category> selectCategoryByPage(Map<String, Object> map) {
List<Category> list = this.t.selectCategoryByPage(map);
return list;
} }

8、BaseService接口

package com.jdw.service;

import com.jdw.bean.IModel;
import com.jdw.dao.IMapper;
import com.jdw.dao.impl.BaseDaoImpl; /**
* 共性的泛型化的Service接口
* @author Administrator
*
* @param <M>
* @param <T>
* @param <D>
*/
public interface BaseService<M extends IModel,T extends IMapper<M>, D extends BaseDaoImpl<T,M>> {
int insert(M model); int insertSelective(M model); int updateByPrimaryKeySelective(M model); int updateByPrimaryKey(M model); int deleteByPrimaryKey(int id); M selectByPrimaryKey(int id);
}

9、继承了BaseService接口的CategoryService接口

package com.jdw.service;

import java.util.List;
import java.util.Map; import com.jdw.bean.Category;
import com.jdw.dao.CategoryMapper;
import com.jdw.dao.impl.CategoryDaoImpl; /**
* 继承了BaseService接口的CategoryService接口
* @author Administrator
*
*/
public interface CategoryService extends BaseService<Category,CategoryMapper,CategoryDaoImpl> {
public Map<String,Object> query(String type, Integer page, Integer size);
public void deleteByIds(String ids);
public List<Category> getAll(Map<String,Object> map);
}

10、BaseServiceImpl

package com.jdw.service.impl;

import org.springframework.beans.factory.annotation.Autowired;

import com.jdw.bean.IModel;
import com.jdw.dao.IMapper;
import com.jdw.dao.impl.BaseDaoImpl;
import com.jdw.service.BaseService; /**
* 泛型化的共性service实现
* @author Administrator
*
* @param <M>
* @param <T>
* @param <D>
*/
public class BaseServiceImpl<M extends IModel,T extends IMapper<M>, D extends BaseDaoImpl<T,M>> implements BaseService<M, T, D> { @Autowired
protected D dao; @Override
public int insert(M model) {
int result=dao.insert(model);
return result;
} @Override
public int insertSelective(M model) {
int result=dao.insertSelective(model);
return result;
} @Override
public int updateByPrimaryKeySelective(M model) {
int result=dao.updateByPrimaryKeySelective(model);
return result;
} @Override
public int updateByPrimaryKey(M model) {
int result=dao.updateByPrimaryKey(model);
return result;
} @Override
public int deleteByPrimaryKey(int id) {
int result=dao.deleteByPrimaryKey(id);
return result;
} @Override
public M selectByPrimaryKey(int id) {
M model=dao.selectByPrimaryKey(id);
return model;
} }

11、CategoryServiceImpl,原理同7,不再赘述

package com.jdw.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.springframework.stereotype.Service; import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jdw.bean.Category;
import com.jdw.dao.CategoryMapper;
import com.jdw.dao.impl.CategoryDaoImpl;
import com.jdw.service.CategoryService; @Service("categoryService")
public class CategoryServicImpl extends BaseServiceImpl<Category, CategoryMapper, CategoryDaoImpl>
implements CategoryService { @Override
public void deleteByIds(String ids) { } @Override
public Map<String, Object> query(String type, Integer pageNo, Integer pageSize) {
pageNo = pageNo == null ? 1 : pageNo;
pageSize = pageSize == null ? 10 : pageSize;
PageHelper.startPage(pageNo, pageSize);
List<Category> list = this.dao.selectCategoryByType(type);
for (Category c : list) {
System.out.println(c);
}
// 用PageInfo对结果进行包装
PageInfo<Category> page = new PageInfo<Category>(list); // 测试PageInfo全部属性
/*
* System.out.println(page.getPageNum());
* System.out.println(page.getPageSize());
* System.out.println(page.getStartRow());
* System.out.println(page.getEndRow());
* System.out.println(page.getTotal());
* System.out.println(page.getPages());
* System.out.println(page.getFirstPage());
* System.out.println(page.getLastPage());
* System.out.println(page.isHasPreviousPage());
* System.out.println(page.isHasNextPage());
*/
Map<String, Object> map = new HashMap<String, Object>();
map.put("total", page.getTotal());
map.put("rows", page.getList());
return map;
} @Override
public List<Category> getAll(Map<String, Object> map) { return this.dao.selectCategoryByPage(map);
} }

12、总结说明

  有的人觉的这么写好麻烦啊,又是接口,又是泛型,还是基类的。他们觉得直接Service里面用mapper就行了,又简单又方便,想用哪个mapper就注入哪个mapper。想法有多好,耦合就有多高!

  面向接口会让各模块之间的耦合程度很低,比如哪天你不想用mybatis了,只需要修改dao层的实现就可以了,service层不需要动!如果你service里有mybatis注入代码呢?如果service没有接口的话,controller估计也要改了,跟重做没有什么区别,也许更麻烦,面向接口让代码更规范,重用度更高。一句话,面向接口是各种设计模式的基础。

  泛型让代码更简练,让共性成为共性,让特性更加特性,一目了然!

  

springmvc+mybatis如何分层的更多相关文章

  1. 基于Extjs+SpringMVC+MyBatis+Oracle的B/S信息系统简化开发思路

    要在上层简化就得有下层强大的架构作为支撑,通过采用企业级的各种框架,虽然学习成本高一些,但用好了效率也自然高. 数据层简化: 首先所有表都有名称为ID的主键字段.有与表同名的序列作为自增key. 数据 ...

  2. 如何玩转最新的项目的搭配springmvc+mybatis+Redis+Nginx+tomcat+mysql

    上一次完成nginx+tomcat组合搭配,今天我们就说说,这几个软件在项目中充当的角色: 要想完成这几个软件的组合,我们必须知道和熟悉应用这个框架, 一: Nginx:在项目中大多数作为反向代理服务 ...

  3. Maven + SpringMVC + Mybatis

    使用IDEA配置Maven + SpringMVC + Mybatis [一步一步踩坑详细配置完成] PS:初学,想使用Maven配置一个SpringMVC的开发环境,照着网上的各种图文解说,配置了好 ...

  4. SSM三大框架整合详细教程(Spring+SpringMVC+MyBatis)【转】

    使用SSM(Spring.SpringMVC和Mybatis)已经有三个多月了,项目在技术上已经没有什么难点了,基于现有的技术就可以实现想要的功能,当然肯定有很多可以改进的地方.之前没有记录SSM整合 ...

  5. 解决springmvc+mybatis+mysql中文乱码问题【转】

    这篇文章主要介绍了解决java中springmvc+mybatis+mysql中文乱码问题的相关资料,需要的朋友可以参考下 近日使用ajax请求springmvc后台查询mysql数据库,页面显示中文 ...

  6. Maven创建web项目:SpringMVC+Mybatis 【转】

    IDEA14创建Maven管理的SpringMVC+Mybatis,web项目 项目构建步骤 1.File->New->Project 勾选Create from archetype 点击 ...

  7. 基于Spring+SpringMVC+Mybatis的Web系统搭建

    系统搭建的配置大同小异,本文在前人的基础上做了些许的改动,重写数据库,增加依据权限的动态菜单的实现,也增加了后台返回json格式数据的配置,详细参见完整源码. 主要的后端架构:Spring+Sprin ...

  8. IDEA中maven搭建Spring+SpringMVC+mybatis项目

    一.介绍 使用IDEA搭建maven web项目,整合框架Spring+SpringMVC+mybatis 项目结构图:

  9. 【JavaWeb】Spring+SpringMVC+MyBatis+SpringSecurity+EhCache+JCaptcha 完整Web基础框架(三)

    Spring+SpringMVC MVC呢,现在似乎越来越流行使用SpringMVC框架,我自己用的感觉,是非常好,确实很舒服,配置一开始是麻烦了一点点,但是后续的开发真的是很清爽! SpringMV ...

随机推荐

  1. 关于Android Assets读取文件为File对象

    关于Android Assets读取文件为File对象的问题,在Assets里面放置文件,在使用的时候,一般是使用AssetManger对象,open方法获取InputStream 然后进行其他操作. ...

  2. Ecstore的微信账号绑定会员免登录

    在微信公众号中通过消息交互/自定义菜单,可直接登录Ecstore手机商城.如果想用原商城账号登录,可以通过登录绑定,在后台可以获取登录绑定的链接这个链接可以在微信公众号消息交互场景或自定义菜单中使用, ...

  3. connectionStrings基本配置

    常用connectionStrings配置: <connectionStrings>   <add       name="LocalSqlServer"     ...

  4. Oracle 向上递归、向下递归

    ---- 向上递归select distinct orgguid,dtb_orgguid,orgname from dtba_organization a start with orgguid = ' ...

  5. Google谷歌搜索引擎登录网站 - Blog透视镜

    建置好了网站之后,为了能提升流量或是增加曝光度,Mix通常会到Google谷歌,用手动登录的方式,登录网站,不久之后,搜索引擎就会派遣蜘蛛机器人,来检索你的网站,等一段时间之后,就会出现在搜索引擎内, ...

  6. 【转】Linux驱动模块编译进内核中

    原文网址:http://blog.chinaunix.net/uid-29287950-id-4573481.html BQ27501驱动编译进内核 一.       驱动程序编译进内核的步骤 在 l ...

  7. 用日志文件备份sqlserver

    USE [TestDB] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO )) as ) ),),)),)+ '.bak' backup dat ...

  8. linux常用查看硬件设备信息命令(转载)

    系统 # uname -a                                       # 查看内核/操作系统/CPU信息 # head -n 1 /etc/issue         ...

  9. mongoDb c driver

    1,yum dependencies Centos,RHEL Fedora: $ sudo yum install git gcc automake autoconf libtool Debian: ...

  10. FTA

    FTA - 维基百科,自由的百科全书 FTA 维基百科,自由的百科全书   跳转至: 导航. 搜索 FTA可以指: 自由贸易协定(Free Trade Agreement) 自由贸易区(Free Tr ...