旧方法的弊端

在Mybatis笔记一中,我们使用命名空间+id的方式实现了Mybatis的执行,不过这里的命名空间是我们随便写的,id也是随意写的,这种方式其实是有弊端的,例如我们在执行的时候用的这个

  list =sqlSession.selectList("Message.selectOneMessage",1);

这里有一个不好的地方,第二个参数是Object类型的,我们输入1,但是没办法保证类型安全,没办法保证其他人调用的时候也输入Integer类型,所以这次,我要换一个类型安全的方式,接口式编程

接口式编程

使用接口,首先我们要新建一个接口,我起名为MessageMapper

package com.vae.springboot.study.mapper;
import com.vae.springboot.study.bean.Message; public interface MessageMapper {
public Message getMsgById(Integer id);
}

有了接口之后,我们的Message.xml类的配置文件需要和接口进行绑定一下

首先,namespace从自定义的 Message换成了接口的地址

其次,每个语句Id换成了接口的名称,而不是随意写的了,更换之后的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 -->
<mapper namespace="com.vae.springboot.study.mapper.MessageMapper">
<!--
数据库查询数据
insert、select、delete、update:sql语句类型
id:sql语句唯一标识
resultType:结果返回值类型-包名+类名 或 基本数据类型
parameterType:匹配字段值-包名+类名 或 基本数据类型
-->
<select id="getMsgById" parameterType="com.vae.springboot.study.bean.Message" resultType="com.vae.springboot.study.bean.Message">
select * from message where ID=#{ID}
</select> </mapper>

可以对比笔记一发现,我们更改,只改了两个地方

<mapper namespace="com.vae.springboot.study.mapper.MessageMapper">
<select id="getMsgById" parameterType="com.vae.springboot.study.bean.Message" resultType="com.vae.springboot.study.bean.Message">
select * from message where ID=#{ID}
</select>

namespace和id

最后,我们来调用一下,SqlSessionFactory使用的频率太高了,所以上一篇我已经介绍了,封装成DBAcess类了

  @Test
public void getOneNew() throws IOException {
DBAcess dbAcess=new DBAcess();
SqlSession sqlSession = dbAcess.getSqlSession();
try {
MessageMapper mapper =sqlSession.getMapper (MessageMapper.class);
Message message=mapper.getMsgById(1);
System.out.println(mapper);
System.out.println(message.getId()+message.getCommand()+message.getDescription());
}finally {
sqlSession.close();
}

执行一下,结果也是ok的,这里需要解释一下

我们使用的是接口,接口怎么可能调用方法呢?原因是自动的帮我们生成了一个实现类:代理对象

可以看看我执行后输出的结果

org.apache.ibatis.binding.MapperProxy@38d08cb5

1查看精彩内容

Proxy代理类。

接口式编程的好处

  1. 返回值确定
  2. 参数确定,我写Integer,你就只能传入Integer
  3. 我不仅可以使用Mybatis,也可以使用Hibernate或者其他的工具,耦合度降低了

接口式编程的增删改查

上面我演示了接口式编程的查,现在演示一下其他的操作,增删改查

先来看看我的实体类的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 -->
<mapper namespace="com.website.mapper.ProductMapper">
<!--
数据库查询数据
insert、select、delete、update:sql语句类型
id:sql语句唯一标识
resultType:结果返回值类型-包名+类名 或 基本数据类型
parameterType:匹配字段值-包名+类名 或 基本数据类型
--> <select id="getAll" parameterType="com.website.entity.Product" resultType="com.website.entity.Product">
select * from Product where 1=1
<if test="name !=null and !&quot;&quot;.equals(name.trim())">and name =#{name}</if>
<if test="type !=null and !&quot;&quot;.equals(type.trim())">and type like '%' #{type} '%'</if>
</select> <select id="getOneById" parameterType="com.website.entity.Product" resultType="com.website.entity.Product">
select * from Product where ID=#{ID}
</select> <insert id="insert" parameterType="com.website.entity.Product">
insert into Product values(#{id},#{name},#{price},#{type})
</insert> <delete id="delete" parameterType="Integer">
delete from Product where ID = #{id}
</delete> <update id="update" parameterType="com.website.entity.Product">
update Product set id=#{id},name=#{name},price=#{price},type=#{type} where id =#{id};
</update> </mapper>

这里面,增删改查,我都写了。可以发现一点,我在插入或者更新的时候,需要对一个对象进行操作,我写的参数都是对象实体类的字段名,这一点很方便。

最后看看我的测试类吧

package com.website.controller;

import com.website.DB.DBAcess;
import com.website.entity.Product;
import com.website.mapper.ProductMapper;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test; import java.io.IOException;
import java.util.ArrayList;
import java.util.List; import static org.junit.Assert.*; public class ProductControllerTest { @Test
public void list() throws IOException {
Product product=new Product();
List<Product> list=new ArrayList<>();
DBAcess dbAcess=new DBAcess();
SqlSession sqlSession = dbAcess.getSqlSession();
try {
ProductMapper mapper =sqlSession.getMapper (ProductMapper.class);
list =mapper.getAll(product);
System.out.println(list.size());
System.out.println(list);
}finally {
sqlSession.close();
}
} @Test
public void getOne() throws IOException {
Product product=new Product();
DBAcess dbAcess=new DBAcess();
SqlSession sqlSession = dbAcess.getSqlSession();
try {
ProductMapper mapper =sqlSession.getMapper (ProductMapper.class);
product=mapper.getOneById(1);
System.out.println("------------"+product.getId());
System.out.println("------------"+product.getName());
System.out.println("------------"+product.getType());
System.out.println("------------"+product.getPrice());
}finally {
sqlSession.close();
}
} @Test
public void delete() throws IOException {
DBAcess dbAcess=new DBAcess();
SqlSession sqlSession = dbAcess.getSqlSession();
try {
ProductMapper mapper =sqlSession.getMapper (ProductMapper.class);
mapper.delete(2);
sqlSession.commit();
}finally {
sqlSession.close();
}
} @Test
public void insert() throws IOException {
Product product=new Product();
product.setId(3);
product.setName("IMac");
product.setType("电脑");
product.setPrice(15000.0); DBAcess dbAcess=new DBAcess();
SqlSession sqlSession = dbAcess.getSqlSession();
try {
ProductMapper mapper =sqlSession.getMapper (ProductMapper.class);
mapper.insert(product);
sqlSession.commit();
}finally {
sqlSession.close();
}
} @Test
public void update() throws IOException {
Product product=new Product();
product.setId(3);
product.setName("IMac Pro");
product.setType("台式电脑");
product.setPrice(14500.0); DBAcess dbAcess=new DBAcess();
SqlSession sqlSession = dbAcess.getSqlSession();
try {
ProductMapper mapper =sqlSession.getMapper (ProductMapper.class);
mapper.update(product);
sqlSession.commit();
}finally {
sqlSession.close();
}
} }

可以发现,还是有不少的重复代码的,不爽啊。这个简单的操作上我还是喜欢JPA

注意:查询不需要commit,其他的增删改都需要commit

Mybatis笔记二:接口式编程的更多相关文章

  1. 通过自动回复机器人学Mybatis 笔记:接口式编程

    [接口式编程]尚未遇见Spring --> 代码量反而增加 1.增加约定,减少犯错的可能(不用直接去写字符串 修改点1:命名空间 修改点2:增加接口,方法名与配置文件中的id对应 package ...

  2. 通过自动回复机器人学Mybatis笔记:接口式编程

    [接口式编程]尚未遇见Spring --> 代码量反而增加 1.增加约定,减少犯错的可能(不用直接去写字符串 修改点1:命名空间 修改点2:增加接口,方法名与配置文件中的id对应 package ...

  3. MyBatis的接口式编程Demo

    很久没细看过MyBatis了,时间一长就容易忘记. 下面是一个接口式编程的例子. 这里的例子一共分为4步: 1 首先要有一个namespace为接口的全类名的映射文件,该例中是 IMyUser.xml ...

  4. MyBatis3-topic04,05 -接口式编程

    笔记要点 /**接口式编程: * 1. 原生: Dao 接口-->Dao接口的实现类 * mybatis: Mapper --> 有一个与之对应的 XXMapper.xml * 2. Sq ...

  5. MyBatis源码解析【7】接口式编程

    前言 这个分类比较连续,如果这里看不懂,或者第一次看,请回顾之前的博客 http://www.cnblogs.com/linkstar/category/1027239.html 修改例子 在我们实际 ...

  6. mybaits接口式编程

    Mybatis是接口式编程实现对.xml中sql语句的执行,其过程如下(取自慕课网视频<通过自动回复机器人学Mybatis---加强版>): 1.加载配置信息2.通过加载配置信息加载一个代 ...

  7. 早期MyBatis开发与接口式Mybatis开发的简介

    早期MyBatis开发与接口式Mybatis开发的简介 一.早期版本的myBatis使用 导jar包            1.配置mybatis.xml的配置文件                1) ...

  8. MyBatis笔记二:配置

    MyBatis笔记二:配置 1.全局配置 1.properites 这个配置主要是引入我们的 properites 配置文件的: <properties resource="db.pr ...

  9. Scala学习教程笔记二之函数式编程、Object对象、伴生对象、继承、Trait、

    1:Scala之函数式编程学习笔记: :Scala函数式编程学习: 1.1:Scala定义一个简单的类,包含field以及方法,创建类的对象,并且调用其方法: class User { private ...

随机推荐

  1. 一条命令停止所有lxc容器,删除所有lxc容器

    for i in $(virsh -c lxc:/// list | grep -v 'Id' | awk '{print $2}');do virsh -c lxc:/// destroy ${i} ...

  2. Matplotlib学习---用matplotlib画雷达图(radar chart)

    雷达图常用于对多项指标的全面分析.例如:HR想要比较两个应聘者的综合素质,用雷达图分别画出来,就可以进行直观的比较. 用Matplotlib画雷达图需要使用极坐标体系,可点击此链接,查看对极坐标体系的 ...

  3. 【AGC002F】Leftmost Ball DP 数学

    题目大意 有\(n\)种颜色的球,每种\(m\)个.现在zjt把这\(nm\)个球排成一排,然后把每种颜色的最左边的球染成第\(n+1\)种颜色.求最终的颜色序列有多少种,对\(1000000007\ ...

  4. ans Single VIP LLB and SLB config

    ans Single VIP LLB and SLB config 配置命令: # 配置设备工作模式和开启的功能 > enable ans mode FR MBF Edge USNIP L3 P ...

  5. MT【279】分母为根式的两个函数

    函数$f(x)=\dfrac{3+5\sin x}{\sqrt{5+4\cos x+3\sin x}}$的值域是____ 分析:注意到$f(x)=\sqrt{10}\dfrac{5\sin x+3}{ ...

  6. Leetcode 215. 数组中的第K个最大元素 By Python

    在未排序的数组中找到第 k 个最大的元素.请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素. 示例 1: 输入: [3,2,1,5,6,4] 和 k = 2 输出: 5 ...

  7. linux系统下saltstack的安装和配置

    Saltstack是一个新的基础设施管理工具,两大功能:远程执行和配置管理. Saltstack使用Python开发,是一个非常简单易用和轻量级的管理工具.由Master和Minion构成,通过Zer ...

  8. luogu3119/bzoj3887 草鉴定 (tarjan缩点+spfa)

    首先缩一波点,就变成了一个DAG,边权是出点的大小 那我们走到某个点的时候可能会有两种状态:已经走过反边或者没走过 于是就把一个点拆成两层(x和x+N),第二层的点表示我已经走过反边了,每层中的边和原 ...

  9. Chinese Mahjong UVA - 11210 (DFS)

    先记录下每一种麻将出现的次数,然后枚举每一种可能得到的麻将,对于这个新的麻将牌,去判断可不可能胡,如果可以胡,就可以把这张牌输出出来. 因为eye只能有一张,所以这个是最好枚举的,就枚举每张牌成为ey ...

  10. NOIP2018保卫王国

    题目大意:给一颗有点权的树,每次规定两个点选还是不选,求这棵树的最小权点覆盖. 题解 ZZ码农题. 要用动态dp做,这题就是板子,然鹅并不会,留坑代填. 因为没有修改,所以可以静态倍增. 我们先做一遍 ...