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. 在C++代码中调用L脚本语言

    L脚本语言同意被其他编程语言调用.如C++,非常easy.仅仅要在宿主语言中载入L脚本引擎的动态库 直接调用这两个函数就能够了 extern "C" int __stdcall S ...

  2. [git push] rejecteded 问题的解决方法

    错误信息: hint: Updates were rejected because a pushed branch tip is behind its remote hint: counterpart ...

  3. mysql default null empty string concat varchar text

    text不可设置默认值 null  empty string   前者update 初始值时 我响应,但不报错

  4. Cocos2d-x 3.2编译生成Android程序出错Error running command, return code: 2的解决方法

    用Cocos2d-x 3.2正式版创建项目,结果使用cocos compile -p android编译生成APK程序,结果悲剧了,出现以下错误. Android NDK: Invalid APP_S ...

  5. Flask开启多线程、多进程

    一.参数 app.run()中可以接受两个参数,分别是threaded和processes,用于开启线程支持和进程支持. 二.参数说明 1.threaded : 多线程支持,默认为False,即不开启 ...

  6. python-----删除文件到回收站

    python删除文件一般使用os.remove,但这样删是直接删除文件,不删到回收站的,那么想删除文件到回收站怎么办? 这时,就需要使用shell模块了 from win32com.shell imp ...

  7. centOS封装

    前言 在实际工作中,CentOS的安装需要设置的语言.键盘模式.时区等信息都存在很大程度上的雷同型.并且,安装完成后的一些设置工作也都是一样的.这些工作都可以在安装操作系统的时候自动完成.最终做到,安 ...

  8. 学生表、课程表、 成绩表 、教师表sql练习

    转自:http://yuncode.net/code/c_58df7a8ca687e58 1.查询“1”课程比“2”课程成绩高的所有学生的学号: SELECT t1.student_id FROM   ...

  9. 插入CSS的方法

    传送门    选择器  selector {declaration1; declaration2; ... declarationN }   例:   p { text-aligh:center; } ...

  10. git 删除本地仓库

    更新: 2017/06/27 修改格式,备注mac下的命令没测试过   windows: rm .git/ mac: sudo rm -rf .git/ 没验证