MyBatis接口代理

MyBatis接口代理:

  • 采用 Mybatis 的代理开发方式实现 DAO 层的开发,这种方式是目前的主流方式。
  • Mapper 接口开发方法只需要程序员编写Mapper 接口(相当于Dao 接口),由Mybatis 框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。

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

  1. 映射配置文件中的namespace与mapper接口的类名相同
  2. 映射配置文件中的增删改查标签的id属性要和Mappe接口中的方法名相同
  3. 映射配置文件中的增删改查标签的parameterType属性要和Mappe接口中的方法参数相同
  4. 映射配置文件中的增删改查标签的resultType属性要和Mappe接口中方法的返回值相同
接口代理原理:

分析动态代理对象如何生成的?

通过动态代理开发模式,我们只编写一个接口,不写实现类,我们通过 getMapper() 方法最终获取到 org.apache.ibatis.binding.MapperProxy 代理对象,然后执行功能,而这个代理对象正是 MyBatis 使用了 JDK 的动态代理技术,帮助我们生成了代理实现类对象。从而可以进行相关持久化操作。

分析方法是如何执行的?

动态代理实现类对象在执行方法的时候最终调用了 mapperMethod.execute() 方法,这个方法中通过 switch 语句根据操作类型来判断是新增、修改、删除、查询操作,最后一步回到了 MyBatis 最原生的 SqlSession 方式来执行增删改查。

接口代理实现演示:

  1. 编写StudentMapper接口
public interface StudentMapper {//查询全部public abstract List<Student> selectAll();//根据id查询public abstract Student selectById(Integer id);//新增数据public abstract Integer insert(Student stu);//修改数据public abstract Integer update(Student stu);//删除数据public abstract Integer delete(Integer id);
}
  1. Service接口
public interface StudentService {//查询全部public abstract List<Student> selectAll();//根据id查询public abstract Student selectById(Integer id);//新增数据public abstract Integer insert(Student stu);//修改数据public abstract Integer update(Student stu);//删除数据public abstract Integer delete(Integer id);
}
  1. 映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!--MyBatis的DTD约束-->
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--mapper:核心根标签namespace属性:名称空间
-->
<mapper namespace="com.mybatis.mapper.StudentMapper"><!--select:查询功能的标签id属性:唯一标识resultType属性:指定结果映射对象类型parameterType属性:指定参数映射对象类型--><select id="selectAll" resultType="student">SELECT * FROM student</select><select id="selectById" resultType="student" parameterType="int">SELECT * FROM student WHERE id = #{id}</select><!--对于增删改返回的都是影响行数,所以resultType属性可以不写--><insert id="insert" parameterType="student">INSERT INTO student VALUES (#{id},#{name},#{age})</insert><update id="update" parameterType="student">UPDATE student SET name = #{name},age = #{age} WHERE id = #{id}</update><delete id="delete" parameterType="int">DELETE FROM student WHERE id = #{id}</delete>
</mapper>
  1. Service实现类
public class StudentMapperImpl implements StudentService {@Overridepublic List<Student> selectAll() {List<Student> list = null;SqlSession sqlSession = null;InputStream rs = null;try {// 加载核心配置文件rs = Resources.getResourceAsStream("MybatisConfig.xml");// 获取工厂对象SqlSessionFactory build = new SqlSessionFactoryBuilder().build(rs);// 获取SqlSession对象sqlSession = build.openSession(true);// 获取接口实现类对象StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);// 通过实现类对象调用方法,接收结果list = mapper.selectAll();} catch (IOException e) {e.printStackTrace();} finally {// 释放资源SSif (sqlSession != null) {sqlSession.close();}if (rs != null) {try {rs.close();} catch (IOException e) {e.printStackTrace();}}}// 返回结果return list;}@Overridepublic Student selectById(Integer id) {Student stu = null;SqlSession sqlSession = null;InputStream rs = null;try {// 加载核心配置文件rs = Resources.getResourceAsStream("MybatisConfig.xml");// 获取工厂对象SqlSessionFactory build = new SqlSessionFactoryBuilder().build(rs);// 获取SqlSession对象sqlSession = build.openSession(true);// 获取接口实现类对象StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);// 通过实现类对象调用方法,接收结果stu = mapper.selectById(id);} catch (IOException e) {e.printStackTrace();} finally {// 释放资源SSif (sqlSession != null) {sqlSession.close();}if (rs != null) {try {rs.close();} catch (IOException e) {e.printStackTrace();}}}return stu;}@Overridepublic Integer insert(Student stu) {Integer result = null;SqlSession sqlSession = null;InputStream rs = null;try {// 加载核心配置文件rs = Resources.getResourceAsStream("MybatisConfig.xml");// 获取工厂对象SqlSessionFactory build = new SqlSessionFactoryBuilder().build(rs);// 获取SqlSession对象sqlSession = build.openSession(true);// 获取接口实现类对象StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);// 通过实现类对象调用方法,接收结果result = mapper.insert(stu);} catch (IOException e) {e.printStackTrace();} finally {// 释放资源SSif (sqlSession != null) {sqlSession.close();}if (rs != null) {try {rs.close();} catch (IOException e) {e.printStackTrace();}}}return result;}@Overridepublic Integer update(Student stu) {Integer result = null;SqlSession sqlSession = null;InputStream rs = null;try {// 加载核心配置文件rs = Resources.getResourceAsStream("MybatisConfig.xml");// 获取工厂对象SqlSessionFactory build = new SqlSessionFactoryBuilder().build(rs);// 获取SqlSession对象sqlSession = build.openSession(true);// 获取接口实现类对象StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);result = mapper.update(stu);} catch (IOException e) {e.printStackTrace();} finally {// 释放资源SSif (sqlSession != null) {sqlSession.close();}if (rs != null) {try {rs.close();} catch (IOException e) {e.printStackTrace();}}}return result;}@Overridepublic Integer delete(Integer id) {Integer result = null;SqlSession sqlSession = null;InputStream rs = null;try {// 加载核心配置文件rs = Resources.getResourceAsStream("MybatisConfig.xml");// 获取工厂对象SqlSessionFactory build = new SqlSessionFactoryBuilder().build(rs);// 获取SqlSession对象sqlSession = build.openSession(true);// 获取接口实现类对象StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);result = mapper.delete(id);} catch (IOException e) {e.printStackTrace();} finally {// 释放资源SSif (sqlSession != null) {sqlSession.close();}if (rs != null) {try {rs.close();} catch (IOException e) {e.printStackTrace();}}}return result;}
}
  1. 测试类
public class StuTest {// 创建业务层对象private StudentService  service = new StudentMapperImpl();//查询全部功能测试@Testpublic void selectAll() {List<Student> students = service.selectAll();for (Student stu : students) {System.out.println(stu);}}//根据id查询功能测试@Testpublic void selectById() {Student stu = service.selectById(3);System.out.println(stu);}//新增功能测试@Testpublic void insert() {Student stu = new Student(4,"赵六",26);Integer result = service.insert(stu);System.out.println(result);}//修改功能测试@Testpublic void update() {Student stu = new Student(4,"赵六",16);Integer result = service.update(stu);System.out.println(result);}//删除功能测试@Testpublic void delete() {Integer result = service.delete(4);System.out.println(result);}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/572205.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

编译OSG的FreeType插件时注意的问题

使用自己编译的freetype.lib&#xff0c;在编译osgdb_freetype插件项目时&#xff0c;报错LINK错误&#xff0c;找不到png的一堆函数 最简单的方式是不要使用PNG编译freetype。记住不要犯贱。 转载于:https://www.cnblogs.com/coolbear/p/7205906.html

openresty总结

协程 1.例如当获取的数据没有前后依赖关系时&#xff0c;可以使用ngx.thread.spawn和ngx.thread.wait同时从数据库不同的库、表或者不同来源&#xff08;mysql&#xff0c;redis等&#xff09;获取数据。https://github.com/openresty/lua-nginx-module#ngxthreadspawnhttps://…

PageHelper分页插件使用

分页插件PageHelper&#xff1a; MyBatis没有分页功能&#xff0c;需要手动编写LIMIT语句&#xff0c;可以使用第三方的插件来对功能进行扩展&#xff0c;分页助手PageHelper是将分页的复杂操作进行封装&#xff0c;使用简单的方式即可获得分页的相关数据 PageInfo&#xff1a;…

jquery插件开发通用框架

2017-07-24 更新&#xff1a;增加单例模式。 jquery插件开发框架代码&#xff1a; /** 插件编写说明&#xff1a;* 1、插件命名&#xff1a;jquery.[插件名].js&#xff0c;如jquery.plugin.js* 2、对象方法添加到jQuery.fn上&#xff0c;全局方法添加到jQuery对象本身上* 3、插…

Mybatis多表模型

多表模型&#xff1a; 多表模型分类 一对一&#xff1a;在任意一方建立外键&#xff0c;关联对方的主键。一对多&#xff1a;在多的一方建立外键&#xff0c;关联一的一方的主键。多对多&#xff1a;借助中间表&#xff0c;中间表至少两个字段&#xff0c;分别关联两张表的主键…

关于zkfc与zkserver频繁断开的问题

详见http://blog.csdn.net/dslztx/article/details/51596951转载于:https://www.cnblogs.com/roger888/p/7211625.html

高动态范围红外图像压缩

BF&DRC 近期看了一篇高动态范围红外图像压缩的文章&#xff0c;《New technique for the visualization of high dynamic range infrared images》.这篇文章主要利用双边滤波器把宽动态红外图像切割为基本图像和细节图像&#xff0c;再分别对基本图像和细节图像进行处理。对…

Mybatis构建sql语法

构建sql&#xff1a; 之前通过注解开发时&#xff0c;相关 SQL 语句都是自己直接拼写的。一些关键字写起来比较麻烦、而且容易出错。MyBatis 给我们提供了 org.apache.ibatis.jdbc.SQL 功能类&#xff0c;专门用于构建 SQL 语句 常用方法&#xff1a; 查询功能的实现&#xf…

Mqtt协议IOS端移植3

ServerMqFramework.h #import "MqttFramework.h"interface ServerMqFramework : MqttFramework/*** brief 得到模块控制器的句柄单例** param [in] N/A* param [out] N/A* return void* note*/(ServerMqFramework*)getMQttServerFrameInstance;- (int)callBusine…

java第三课,流程控制语句

流程控制语句条件语句&#xff1a;if语句&#xff1a;*if&#xff08;条件 boolean类型&#xff09;{ true }*if(boolean表达式){true}else&#xff5b;false结果&#xff5d;*多重 if else if(){}else if(){}else *嵌套ifSwitch语句&#xff1a;*switch(表达式){ case…

在cli命令行上显示当前数据库,以及查询表的行头信息

在$HIVE_HOME/conf/hive-site.xml文件下加入以下配置文件 <property><name>hive.cli.print.header</name><value>true</value><description>Whether to print the names of the columns in query output.</description> </proper…

两点之间最短路径:弗洛伊德算法

弗洛伊德算法是计算无向有权图中两点间最短路径的算法&#xff0c;复杂度为O(n^3)。其思路是将两点间距离分为过&#xff08;指定的&#xff09;第三点或是不过&#xff0c;然后取它们的最小值&#xff0c;如此循环就可以得到两点之间真正的最小值。 void floyd() {for (int k …

最常用的JavaScript 事件

JavaScript 事件&#xff1a; 事件指的就是当某些组件执行了某些操作后&#xff0c;会触发某些代码的执行。 更多事件&#xff1a;https://www.w3school.com.cn/jsref/dom_obj_event.asp 常用的事件&#xff1a; 属性触发时机onabort图像加载被中断onblur元素失去焦点onchange…

Codevs 1025 选菜

1025 选菜 时间限制: 1 s空间限制: 128000 KB题目等级 : 黄金 Gold题解题目描述 Description在小松宿舍楼下的不远处&#xff0c;有PK大学最不错的一个食堂——The Farmer’s Canteen&#xff08;NM食堂&#xff09;。由于该食堂的菜都很不错&#xff0c;价格也公道&#xff0c…

SAS笔记(2) RETAIN语句

本文重点&#xff1a; 使用RETIAN,INPUT在每次循环执行时保留上一次PDV中的变量值。SUM语句和SET语句会自动RETAIN变量。1. RETAIN语句 1.1 Example 1 先来看看在DATA步不使用和使用RETAIN语句的差异 没有使用RETAIN: DATA WITHOUT_1;PUT "Before the INPUT statement: &…

Hive优化策略

hive优化目标 在有限的资源下&#xff0c;运行效率高。常见问题 数据倾斜、Map数设置、Reduce数设置等 hive运行 查看运行计划 explain [extended] hql 例子 explain select no,count(*) from testudf group by no; explain extended select no,count(*) from testudf group …

POJ 3268 Silver Cow Party (最短路径)

POJ 3268 Silver Cow Party &#xff08;最短路径&#xff09; Description One cow from each of N farms (1 ≤ N ≤ 1000) conveniently numbered 1..N is going to attend the big cow party to be held at farm #X (1 ≤ X ≤ N). A total of M (1 ≤ M ≤ 100,000) unidi…

GPU性能实时监测的实用工具

大家好,我是爱编程的喵喵。双985硕士毕业,现担任全栈工程师一职,热衷于将数据思维应用到工作与生活中。从事机器学习以及相关的前后端开发工作。曾在阿里云、科大讯飞、CCF等比赛获得多次Top名次。现为CSDN博客专家、人工智能领域优质创作者。喜欢通过博客创作的方式对所学的…

条件随机场-应用

今天介绍CRFs在中文分词中的应用 工具&#xff1a;CRF,可以去 https://taku910.github.io/crfpp/ 下载&#xff0c;训练数据和测试数据可以考虑使用bakeoff2005,这是链接 http://sighan.cs.uchicago.edu/bakeoff2005/ 首先需要了解一些概念 字标记法——统计分词模型常用的方法…

Codeforces-808D Array Division (multiset 折半???)

题目链接&#xff1a; http://codeforces.com/problemset/problem/808/D 题意: 给定一个数列&#xff0c;移动0或1个数字&#xff0c;使数列能从某个位置分开前后两半的和相等。 思路&#xff1a; from: http://www.cnblogs.com/robin1998/p/6864278.html 我们可以假想有个隔板…