Mapper动态代理开发方式

实现原理:

Mapper接口开发方法只需要程序员编写Mapper接口(相当于Dao接口),由Mybatis框架根据接口定义创建接口的动态代理对象。

Mapper接口开发需要遵循以下规范:

1、 Mapper.xml文件中的namespace与mapper接口的类路径相同。

2、 Mapper接口方法名和Mapper.xml中定义的每个statement的id相同。

3、 Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql 的parameterType的类型相同。

4、Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同。

一、定义UserMapper.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"> <!-- namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离
注意:使用mapper代理方法开发,namespace有特殊重要的作用
namespace为其接口地址 另外接口中的方法名要和配置文件中的statement id一致 方法中形参类型也要和parametertype一致
返回值类型也要与配置文件中resultType指定的类型一致 遵循该规范 mybatis可以自动生成mapper接口的实现类代理对象 -->
<mapper namespace="cn.itcast.mybatis.mapper.UserMapper"> <!-- 定义sql片段 id:sql片段的唯 一标识 经验:是基于单表来定义sql片段,这样话这个sql片段可重用性才高 在sql片段中不要包括
where -->
<sql id="query_user_where">
<if test="userCustom!=null">
<if test="userCustom.sex!=null and userCustom.sex!=''">
and user.sex = #{userCustom.sex}
</if>
<if test="userCustom.username!=null and userCustom.username!=''">
and user.username LIKE '%${userCustom.username}%'
</if>
<!-- <if test="ids!=null"> 使用 foreach遍历传入ids collection:指定输入 对象中集合属性 item:每个遍历生成对象中
open:开始遍历时拼接的串 close:结束遍历时拼接的串 separator:遍历的两个对象中需要拼接的串 使用实现下边的sql拼接: AND
(id=1 OR id=10 OR id=16) <foreach collection="ids" item="user_id" open="AND
(" close=")" separator="or"> 每个遍历需要拼接的串 id=#{user_id} </foreach> 实现 “ and
id IN(1,10,16)”拼接 <foreach collection="ids" item="user_id" open="and id IN("
close=")" separator=","> 每个遍历需要拼接的串 #{user_id} </foreach> </if> -->
</if>
</sql> <!-- 定义resultMap 将SELECT id id_,username username_ FROM USER 和User类中的属性作一个映射关系
type:resultMap最终映射的java对象类型,可以使用别名 id:对resultMap的唯一标识 -->
<resultMap type="user" id="userResultMap">
<!-- id表示查询结果集中唯一标识 column:查询出来的列名 property:type指定的pojo类型中的属性名 最终resultMap对column和property作一个映射关系
(对应关系) -->
<id column="id_" property="id" />
<!-- result:对普通名映射定义 column:查询出来的列名 property:type指定的pojo类型中的属性名 最终resultMap对column和property作一个映射关系
(对应关系) -->
<result column="username_" property="username" /> </resultMap> <select id="findUserByIdResultMap" parameterType="int"
resultMap="userResultMap">
select id id_ ,username username_ from user where id=#{id}
</select> <!-- 在 映射文件中配置很多sql语句 -->
<!-- 需求:通过id查询用户表的记录 -->
<!-- 通过 select执行数据库查询 id:标识 映射文件中的 sql 将sql语句封装到mappedStatement对象中,所以将id称为statement的id
parameterType:指定输入 参数的类型,这里指定int型 #{}表示一个占位符号 #{id}:其中的id表示接收输入 的参数,参数名称就是id,如果输入
参数是简单类型,#{}中的参数名可以任意,可以value或其它名称 resultType:指定sql输出结果 的所映射的java对象类型,select指定resultType表示将单条记录映射成的java对象。 -->
<select id="findUserById" parameterType="int" resultType="user">
select
* from user where id=#{id}
</select> <!-- 用户信息综合查询 #{userCustom.sex}:取出pojo包装对象中性别值 ${userCustom.username}:取出pojo包装对象中用户名称 -->
<select id="findUserList"
parameterType="cn.itcast.mybatis.po.UserQueryVo"
resultType="cn.itcast.mybatis.po.UserCustom">
SELECT * FROM USER
<!-- where可以自动去掉条件中的第一个and -->
<where>
<!-- 引用sql片段 的id,如果refid指定的id不在本mapper文件中,需要前边加namespace -->
<include refid="query_user_where"></include>
<!-- 在这里还可以引用其它的sql片段 -->
</where>
</select> <!-- 根据用户名称模糊查询用户信息,可能返回多条 resultType:指定就是单条记录所映射的java对象 类型 ${}:表示拼接sql串,将接收到参数的内容不加任何修饰拼接在sql中。
使用${}拼接sql,引起 sql注入 ${value}:接收输入 参数的内容,如果传入类型是简单类型,${}中只能使用value -->
<select id="findUserByName" parameterType="java.lang.String"
resultType="user">
select * from user where username like '%${value}%'
</select>
<!-- 添加用户 parameterType:指定输入 参数类型是pojo(包括 用户信息) #{}中指定pojo的属性名,接收到pojo对象的属性值,mybatis通过OGNL获取对象的属性值 -->
<insert id="insertUser"
parameterType="cn.itcast.mybatis.po.User">
<!-- 将插入数据的主键返回,返回到user对象中 SELECT LAST_INSERT_ID():得到刚insert进去记录的主键值,只适用与自增主键
keyProperty:将查询到主键值设置到parameterType指定的对象的哪个属性 order:SELECT LAST_INSERT_ID()执行顺序,相对于insert语句来说它的执行顺序
resultType:指定SELECT LAST_INSERT_ID()的结果类型 -->
<selectKey keyProperty="id" order="AFTER"
resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
insert into user(username,birthday,sex,address)
value(#{username},#{birthday},#{sex},#{address})
</insert> <delete id="deleteUser" parameterType="int">
delete from user where
id=#{id}
</delete> <update id="updateUser" parameterType="user">
update user set
username=#{username},birthday=#{birthday},sex=#{sex},address=#{address}
where id = #{id}
</update>
</mapper>

二、定义UserMapper.java接口文件

 package cn.itcast.mybatis.mapper;

 import java.util.List;

 import cn.itcast.mybatis.po.User;
import cn.itcast.mybatis.po.UserCustom;
import cn.itcast.mybatis.po.UserQueryVo; public interface UserMapper {
//用户信息的高级查询
public List<UserCustom> findUserList(UserQueryVo userQueryVo) throws Exception;
// 根据id查询用户信息
public User findUserById(int id) throws Exception; // 根据id查询用户信息,使用resultMap输出
public User findUserByIdResultMap(int id) throws Exception; // 根据用户名列查询用户列表
public List<User> findUserByName(String name) throws Exception; // 插入用户
public void insertUser(User user) throws Exception; // 删除用户
public void deleteUser(int id) throws Exception;
}

接口定义有如下特点:

1、  Mapper接口方法名和Mapper.xml中定义的statement的id相同

2、  Mapper接口方法的输入参数类型和mapper.xml中定义的statement的parameterType的类型相同

3、  Mapper接口方法的输出参数类型和mapper.xml中定义的statement的resultType的类型相同


三、在SqlMapConfig.xml文件中加载映射文件

  <!-- 加载映射文件 -->
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>

四、程序测试

 package cn.itcast.mybatis.first;

 import java.io.InputStream;
import java.util.List; import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; import cn.itcast.mybatis.mapper.UserMapper;
import cn.itcast.mybatis.po.User;
import cn.itcast.mybatis.po.UserCustom;
import cn.itcast.mybatis.po.UserQueryVo; public class MybatisFirst2 {
public static void main(String[] args) throws Exception {
// mybatis配置文件
String resource = "sqlMapConfig.xml";
// 得到配置文件流
InputStream inputStream = Resources.getResourceAsStream(resource);
// 创建会话工厂,传入mybatis文件的配置信息
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 通过工厂得到Sqlsession
SqlSession session = sqlSessionFactory.openSession(); UserMapper userMapper = session.getMapper(UserMapper.class);
// User user = userMapper.findUserByIdResultMap(25);
UserQueryVo userQueryVo = new UserQueryVo();
UserCustom userCustom = new UserCustom();
userCustom.setSex("1");
// userCustom.setUsername("三");
userQueryVo.setUserCustom(userCustom);
List<UserCustom> userList = userMapper.findUserList(userQueryVo);
session.commit();
// 释放资源
session.close();
System.out.println(userList); }
}

tips:mybatis官方推荐使用mapper代理方法开发mapper接口,程序员不用编写mapper接口实现类,使用mapper代理方法时,输入参数可以使用pojo包装对象或map对象,保证dao的通用性。

Mybatis学习总结二的更多相关文章

  1. MyBatis学习系列二——增删改查

    目录 MyBatis学习系列一之环境搭建 MyBatis学习系列二——增删改查 MyBatis学习系列三——结合Spring 数据库的经典操作:增删改查. 在这一章我们主要说明一下简单的查询和增删改, ...

  2. MyBatis学习 之 二、SQL语句映射文件(2)增删改查、参数、缓存

    目录(?)[-] 二SQL语句映射文件2增删改查参数缓存 select insert updatedelete sql parameters 基本类型参数 Java实体类型参数 Map参数 多参数的实 ...

  3. MyBatis学习 之 二、SQL语句映射文件(1)resultMap

    目录(?)[-] 二SQL语句映射文件1resultMap resultMap idresult constructor association联合 使用select实现联合 使用resultMap实 ...

  4. 【转】MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作

    [转]MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作 上一篇博文MyBatis学习总结(一)——MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据, ...

  5. MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作(转载)

    本文转载自:http://www.cnblogs.com/jpf-java/p/6013540.html 上一篇博文MyBatis学习总结(一)--MyBatis快速入门中我们讲了如何使用Mybati ...

  6. MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作

    上一篇博文MyBatis学习总结(一)——MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据,算是对MyBatis有一个初步的入门了,今天讲解一下如何使用MyBatis对u ...

  7. Mybatis学习笔记二

    本篇内容,紧接上一篇内容Mybatis学习笔记一 输入映射和输出映射 传递简单类型和pojo类型上篇已介绍过,下面介绍一下包装类型. 传递pojo包装对象 开发中通过可以使用pojo传递查询条件.查询 ...

  8. MyBatis学习笔记(二)——使用MyBatis对表执行CRUD操作

    转自孤傲苍狼的博客:http://www.cnblogs.com/xdp-gacl/p/4262895.html 上一篇博文MyBatis学习总结(一)——MyBatis快速入门中我们讲了如何使用My ...

  9. 二:MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作

    上一篇博文MyBatis学习总结(一)——MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据,算是对MyBatis有一个初步的入门了,今天讲解一下如何使用MyBatis对u ...

  10. mybatis学习笔记(二)-- 使用mybatisUtil工具类体验基于xml和注解实现

    项目结构  基础入门可参考:mybatis学习笔记(一)-- 简单入门(附测试Demo详细过程) 开始体验 1.新建项目,新建类MybatisUtil.java,路径:src/util/Mybatis ...

随机推荐

  1. jmeter获取时间_time 函数

    原始时间戳13位精确到毫秒:${__time(,)} 时间戳精确到秒10位:${__time(/1000,)} 时间日期到年月日2019-04-21:${__time(yyyy-MM-dd,)} 时间 ...

  2. 8.跟我学solr---UpdateRequestProcessor具体解释

    简单介绍 java web开发的同学应该非常熟悉,在开发中常常会使用filter来处理请求中的一些切面需求. solr也提供类似的一种链式结构的handler来满足在加入数据索引请求的时候.通过切片的 ...

  3. FreeRTOS系列第14篇---FreeRTOS任务通知

    注:本文介绍任务通知的基础知识,具体源代码分析见<FreeRTOS高级篇8---FreeRTOS任务通知分析> 每一个RTOS任务都有一个32位的通知值,任务创建时,这个值被初始化为0.R ...

  4. Java后端发出post请求带参数并接收返回的json

    核心代码: 参数格式: “key1=value1&key2=value2” /*** sendUrl    (远程请求的URL)* param    (远程请求参数)* JSONObject  ...

  5. initial ram disk

    1 什么是initial ram disk 它就是一个做好了的文件系统,其存储空间是ram.在kernel启动的第一个阶段,会被mount成根文件系统. 2 为什么需要initial ram disk ...

  6. Windows10、ARM开发板、VMware虚拟机同时连接Internet

    前段时间有人遇到一些网络连接问题,让我帮忙处理,他想让ARM开发板连接外网,可以连接网络数据库,同时保证自己的电脑可以上网. 本来说直接可以连接一个路由器,分配一个内网IP给ARM就可以了,但是当时那 ...

  7. springmvc 用fasterxml.jackson返回son数据

    一,引入fasterxm.jackson包 <dependency> <groupId>com.fasterxml.jackson.core</groupId> & ...

  8. bzoj Strange Way to Express Integers【excrt】

    其实我没看懂题不如说根本没看--都说是excrt板子那就写个板子吧 注意开long long #include<iostream> #include<cstdio> using ...

  9. OpenGL 2D模式

    // // left top 这里设置的默认是左上角 // void push_view2d(int left, int top, int width, int height) { //glPushA ...

  10. Linux学习笔记之Linux系统启动过程

    Linux系统的启动过程可以分为五个阶段: 内核的引导 运行init 系统初始化 建立终端 用户登录系统 1.内核引导: 当计算机打开电源后,首先进行BIOS开机自检,按照BIOS中设置的启动设备(一 ...