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. Unity3D &amp; C# 设计模式--23

     Unity3D & C#Design Patterns 23 design patterns. Creational Patterns 1. Abstract Factory抽象工厂 创 ...

  2. opencv对图像进行边缘及角点检測

    opencv对图像进行边缘及角点检測 先看结果: 代码: // ConsoleApplication1_812.cpp : Defines the entry point for the consol ...

  3. Python爬虫开发【第1篇】【beautifulSoup4解析器】

    CSS 选择器:BeautifulSoup4 Beautiful Soup 也是一个HTML/XML的解析器,主要的功能也是如何解析和提取 HTML/XML 数据. pip 安装:pip instal ...

  4. Eclipse的安装使用

    1.从官网下载最新的Eclipse http://www.eclipse.org/downloads/

  5. 【codevs1306】广播操的游戏

    求字符串内的非空子串的数量 后缀数组!!! #include<algorithm> #include<cstdlib> #include<cstring> #inc ...

  6. charset='utf8mb4'

    charset='utf8mb4' conn = pymysql.connect(host=h, port=pt, user=u, passwd=p, db=db, charset='utf8mb4' ...

  7. YTU 2697: 血型统计

    2697: 血型统计 时间限制: 1 Sec  内存限制: 128 MB 提交: 405  解决: 164 题目描述 黑猫警长在犯罪现场发现了一些血迹,现已经委托检验机构确定了血型,需要统计各种血型的 ...

  8. go语言--time.After

    go语言--time.After https://blog.csdn.net/cyk2396/article/details/78873396 1.源码分析: // After waits for t ...

  9. maven中的三种工程,以及在idea中构建父子工程。

    1.pom工程:用在父级工程或聚合工程中.用来做jar包的版本控制.主要是定义POM文件,将后续各个子模块公用的jar包等统一提出来,类似一个抽象父类 2.war工程:将会打包成war,发布在服务器上 ...

  10. 关于file文件操作的头文件 【LINUX】 (转载)

    转自:http://blog.csdn.net/figo77ll/article/details/3156052 Linux下如果要对文件进行读取访问,需要包含至少以下两个头文件: #inlcude ...