MyBatis之动态代理实现增删改查以及MyBatis-config.xml中读取DB信息文件和SQL中JavaBean别名配置

MyBatis之环境搭建以及实现增删改查

  • 前言
  • 实现步骤
    • 1. 编写MyBatis-config.xml配置文件
    • 2. 编写Mapper.xml文件(增删改查SQL文)
    • 3. 定义PeronMapper接口
    • 4. 编写测试类
      • 1. 执行步骤
      • 2. 代码实例
      • 3. 运行log
  • 开发环境构造图
  • 总结

前言

上一篇文章,我们使用MyBatis传统的方式(namespace+id,非接口式编程),完成了数据库的增删改查操作,今天我们学习动态代理的方式(面向接口编程),简单的说,就是将Mapper.xml(定义数据库增删改查SQL文的文件)中定义的SQLID以方法的形式定义在Interface中,调用其方法,完成数据的增删改查,这种方法,也是大部分项目中使用的方法,环境的搭建和准备工作,还是参看我的上一篇文章。
MyBatis之环境搭建以及实现增删改查


实现步骤

1. 编写MyBatis-config.xml配置文件

编写配置文件,上一篇文章也有介绍,
今天学习两个新功能,第一个就是编写单独的数据库信息文件,在配置文件中读取后,使用${}方式,读取文件中的内容,配置数据库信息,防止硬编码,完成数据库信息统一管理。
首先编写db.properties,将数据库信息定义在此文件中,通常该文件放在classpath下。
示例代码,如下:

my.driver=com.mysql.cj.jdbc.Driver
my.url=jdbc:mysql://192.168.56.88:3306/mysql
my.username=root
my.password=root

在使用< properties>标签,引入到MyBatis-config.xml配置文件中

第二个就是简化参数的写法,上一篇文章,我们看到Mapper.xml文件中,定义SQL的id时,如果输入参数是JavaBean,都是以全类名的形式配置的,这样代码比较冗余,我们使用< typeAliases>< package>标签,批量引用JavaBean,SQL输入输出参数时,可以省略包名的形式,直接使用JavaBean的类名。

MyBatis-config.xml代码如下

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

	<!-- 读取外部数据库信息文件 -->
	<properties resource="db.properties" />

	<!-- 设置JavaBean类型的参数别名 -->
	<typeAliases>
		<package name="xxx.xxx.pojo"/>
	</typeAliases>

  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${my.driver}"/>
        <property name="url" value="${my.url}"/>
        <property name="username" value="${my.username}"/>
        <property name="password" value="${my.password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="xxx/xxx/mapper/PersonMapper.xml"/>
  </mappers>
</configuration>

2. 编写Mapper.xml文件(增删改查SQL文)

编写增删改查的SQL文,这里就不做展开了,需要注意的是,我们已经在配置文件中批量引入JavaBean,我们只需使用类名(person)即可,通常类名开头小写。

<?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="xxx.xxx.entry.personMapper">
  <select id="queryAllPerson" resultType="person">
    select * from person
  </select>
  <select id="queryPersonById" resultType="person" parameterType="int">
    select * from person where id = #{id}
  </select>
  <insert id="addPerson" parameterType="person">
    insert into person values(#{id}, #{name}, #{age}, #{sex})
  </insert>
  <update id="updatePersonById" parameterType="person">
    update person set name = #{name}, age = #{age}, sex = #{sex} where id = #{id}
  </update>
  <delete id="deletePersonById" parameterType="int">
    delete from  person where id = #{id}
  </delete>
</mapper>

3. 定义PeronMapper接口

将Mapper.xml中SQL的id定义到PeronMapper接口中,输入参数和输出参数与SQL的id中的保持一致。
这里需要注意的是,接口文件和Mapper.xml放到同一个文件中,文件名保持一致。

package xxx.xxx.mapper;

import java.util.List;

import xxx.xxx.pojo.Person;

public interface PersonMapper {

	public List<Person> queryAllPerson();

	public Person queryPersonById(int id);

	public int addPerson(Person person);

	public int updatePersonById(Person person);

	public int deletePersonById(int id);
}

4. 编写测试类

1. 执行步骤

  1. 读取MyBatis配置文件
  2. 实例化SqlSessionFactory
  3. 实例化SqlSession
  4. 获取PersonMapper接口
    通过session.getMapper(PersonMapper.class)的方式,获取接口
  5. 执行SQL
  6. 增删改的场合,完成数据提交

2. 代码实例

完成对Person表的增删改查

package xxx.xxx.test;

import java.io.IOException;
import java.io.Reader;
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 xxx.xxx.mapper.PersonMapper;
import xxx.xxx.pojo.Person;

public class TestMyBatis {

	public static void main(String[] args) throws IOException {

		Person person = new Person(1, "zs", 23, true);
		System.err.println("登录前");
		queryPersonById(1);
		addPerson(person);
		System.err.println("登录后");
		queryPersonById(1);

		person = new Person(1, "ls", 24, true);
		System.err.println("更新前");
		queryAllPerson();
		updatePersonById(person);
		System.err.println("更新后");
		queryPersonById(1);

		System.err.println("删除前");
		queryPersonById(1);
		deletePersonById(1);
		System.err.println("删除后");
		queryPersonById(1);

	}

	public static void queryAllPersonUsePersonMapping() throws IOException {

		// 1.读取MyBatis配置文件
		Reader reader = Resources.getResourceAsReader("mybatis-config.xml");

		// 2.实例化SqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

		// 3.实例化SqlSession
		try (SqlSession session = sqlSessionFactory.openSession()) {

			// 4.获取PersonMapper接口
			PersonMapper personMapper = session.getMapper(PersonMapper.class);

			// 5.执行SQL
			List<Person> persons = personMapper.queryAllPerson();
			persons.forEach(System.err::println);
		}

	}

	public static void queryAllPerson() throws IOException {

		// 1.读取MyBatis配置文件
		Reader reader = Resources.getResourceAsReader("mybatis-config.xml");

		// 2.实例化SqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

		// 3.实例化SqlSession
		try (SqlSession session = sqlSessionFactory.openSession()) {

			// 4.获取PersonMapper接口
			PersonMapper personMapper = session.getMapper(PersonMapper.class);

			// 5.执行SQL
			List<Person> persons = personMapper.queryAllPerson();
			persons.forEach(System.err::println);
		}

	}

	public static void queryPersonById(int id) throws IOException {

		// 1.读取MyBatis配置文件
		Reader reader = Resources.getResourceAsReader("mybatis-config.xml");

		// 2.实例化SqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

		// 3.实例化SqlSession
		try (SqlSession session = sqlSessionFactory.openSession()) {

			// 4.获取PersonMapper接口
			PersonMapper personMapper = session.getMapper(PersonMapper.class);

			// 5.执行SQL
			Person person = personMapper.queryPersonById(1);
			System.err.println(person);
		}
	}

	public static void addPerson(Person person) throws IOException {

		// 1.读取MyBatis配置文件
		Reader reader = Resources.getResourceAsReader("mybatis-config.xml");

		// 2.实例化SqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

		// 3.实例化SqlSession
		try (SqlSession session = sqlSessionFactory.openSession()) {

			// 4.获取PersonMapper接口
			PersonMapper personMapper = session.getMapper(PersonMapper.class);

			// 5.执行SQL
			int count = personMapper.addPerson(person);
			System.err.println("登陆件数:" + count);

			// 6.增删改的场合,完成数据提交
			session.commit();
		}
	}

	public static void updatePersonById(Person person) throws IOException {

		// 1.读取MyBatis配置文件
		Reader reader = Resources.getResourceAsReader("mybatis-config.xml");

		// 2.实例化SqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

		// 3.实例化SqlSession
		try (SqlSession session = sqlSessionFactory.openSession()) {

			// 4.获取PersonMapper接口
			PersonMapper personMapper = session.getMapper(PersonMapper.class);

			// 5.执行SQL
			int count = personMapper.updatePersonById(person);
			System.err.println("更新件数:" + count);
			// 6.增删改的场合,完成数据提交
			session.commit();
		}
	}

	public static void deletePersonById(int id) throws IOException {

		// 1.读取MyBatis配置文件
		Reader reader = Resources.getResourceAsReader("mybatis-config.xml");

		// 2.实例化SqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

		// 3.实例化SqlSession
		try (SqlSession session = sqlSessionFactory.openSession()) {

			// 4.获取PersonMapper接口
			PersonMapper personMapper = session.getMapper(PersonMapper.class);

			// 5.执行SQL
			int count = personMapper.deletePersonById(id);
			System.err.println("删除件数:" + count);

			// 6.增删改的场合,完成数据提交
			session.commit();
		}
	}

}

3. 运行log

通过下边的运行log可以看出,完成对Person表的增删改查

登录前
null
登陆件数:1
登录后
Person [id=1, name=zs, age=23]
更新前
Person [id=1, name=zs, age=23]
更新件数:1
更新后
Person [id=1, name=ls, age=24]
删除前
Person [id=1, name=ls, age=24]
删除件数:1
删除后
null

开发环境构造图

在这里插入图片描述

总结

到这里,我们就完成了MyBatis的传统方式和面向接口编程方式完成数据库的增删改查,大家可以动手试试,欢迎留言交流,下篇见。

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

P3647 题解

文章目录 P3647 题解OverviewDescriptionSolutionLemmaProof Main Code P3647 题解 Overview 很好的题&#xff0c;但是难度较大。 模拟小数据&#xff01;——【数据删除】 Description 给定一颗树&#xff0c;有边权&#xff0c;已知这棵树是由这两个操作得到的&#xff1…

Leecode之环形链表

一.题目及剖析 https://leetcode.cn/problems/linked-list-cycle/description/ 这道题就是去判断一个链表是否带环,分两种情况,链表中只有一个元素则一定不带环,链表中有两个及以上的元素则要引入快慢指针 二.思路引入 设置两个快慢指针,快指针走2步,慢指针走1步(不论快慢指…

[BeginCTF]真龙之力

安装程序 双击安装 出现了安装失败的标签&#xff0c;开发者不允许测试。 查看Mainfest入口文件 <?xml version"1.0" encoding"utf-8"?> <manifest xmlns:android"http://schemas.android.com/apk/res/android" android:versionCo…

单片机学习笔记---LED点阵屏显示图形动画

目录 LED点阵屏显示图形 LED点阵屏显示动画 最后补充 上一节我们讲了点阵屏的工作原理&#xff0c;这节开始代码演示&#xff01; 前面我们已经说了74HC595模块也提供了8个LED&#xff0c;当我们不使用点阵屏的时候也可以单独使用74HC595&#xff0c;这8个LED可以用来测试7…

js中new操作符详解

文章目录 一、是什么二、流程三、手写new操作符 一、是什么 在JavaScript中&#xff0c;new操作符用于创建一个给定构造函数的实例对象 例子 function Person(name, age){this.name name;this.age age; } Person.prototype.sayName function () {console.log(this.name) …

零基础学Python(8)— 流程控制语句(上)

前言&#xff1a;Hello大家好&#xff0c;我是小哥谈。流程控制语句是编程语言中用于控制程序执行流程的语句&#xff0c;本节课就带大家认识下Python语言中常见的流程控制语句&#xff01;~&#x1f308; 目录 &#x1f680;1.程序结构 &#x1f680;2.最简单的if语句 &a…

NGINX upstream、stream、四/七层负载均衡以及案例示例

文章目录 前言1. 四/七层负载均衡1.1 开放式系统互联模型 —— OSI1.2 四/七层负载均衡 2. Nginx七层负载均衡2.1 upstream指令2.2 server指令和负载均衡状态与策略2.2.1 负载均衡状态2.2.2 负载均衡策略 2.3 案例 3. Nginx四层负载均衡的指令3.1 stream3.2 upstream指令3.3 四…

掌握Vue,开启你的前端开发之路!

介绍&#xff1a;Vue.js是一个构建数据驱动的Web应用的渐进式框架&#xff0c;它以简洁和轻量级著称。 首先&#xff0c;Vue.js的核心在于其视图层&#xff0c;它允许开发者通过简单的模板语法将数据渲染进DOM&#xff08;文档对象模型&#xff09;。以下是Vue.js的几个重要特点…

哈希表(Hash Table)-----运用实例【通过哈希表来管理雇员信息】(java详解) (✧∇✧)

目录 一.哈希表简介&#xff1a; 实例介绍&#xff1a; 类的创建与说明&#xff1a; 各功能图示&#xff1a; 1.class HashTab{ }; 2. class EmpLinkedList{ }&#xff1b; 3. class Emp{ }&#xff1b; 4.测试&#xff1a; 运行结果&#xff1a; 最后&#xff0c;完整…

LeetCode-第28题-找出字符串中第一个匹配项的下标

1.题目描述 给你两个字符串 haystack 和 needle &#xff0c;请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标&#xff08;下标从 0 开始&#xff09;。如果 needle 不是 haystack 的一部分&#xff0c;则返回 -1 。 2.样例描述 3.思路描述 可以让字符串 …

uTools工具使用

之前发现一款非常有用的小工具&#xff0c;叫uTools&#xff0c;该软件集成了比如进制转换、json格式化、markdown、翻译、取色等等集插件大成&#xff0c;插件市场提供了很多开源插件工具。可以帮助开发人员节省了寻找各种处理工具的时间&#xff0c;非常推荐。 1、软件官方下…

R语言rmarkdown使用

1、安装 install.packages(rmarkdown) library(rmarkdown) install.packages(tinytex) tinytex::install_tinytex() 2、新建R Markdown 3、基本框架 红色框内为YAML&#xff1a;包括标题、作者和日期等 黄色框内为代码块&#xff1a;执行后面的代码&#xff0c;并可以设置展…

LLMs之Llama2 70B:《Self-Rewarding Language Models自我奖励语言模型》翻译与解读

LLMs之Llama2 70B&#xff1a;《Self-Rewarding Language Models自我奖励语言模型》翻译与解读 目录 《Self-Rewarding Language Models》翻译与解读 Abstract 5 Conclusion结论 6 Limitations限制 《Self-Rewarding Language Models》翻译与解读 地址 文章地址&#xff1…

Composition Local

1.显示传参 package com.jmj.jetpackcomposecompositionlocalimport org.junit.Testimport org.junit.Assert.*/*** 显示传参*/ class ExplicitText {private fun Layout(){var color:String "黑色";//参数需要通过层层传递&#xff0c;比较繁琐Text(color)Grid(c…

上位机图像处理和嵌入式模块部署(上位机和下位机通信)

【 声明&#xff1a;版权所有&#xff0c;欢迎转载&#xff0c;请勿用于商业用途。 联系信箱&#xff1a;feixiaoxing 163.com】 一般情况下&#xff0c;如果是纯上位机开发的话&#xff0c;这个时候是不需要上位机和下位机进行通信的。只有上位机做好demo有必要移植到嵌入式模…

使用 Docker 镜像预热提升容器启动效率详解

概要 在容器化部署中,Docker 镜像的加载速度直接影响到服务的启动时间和扩展效率。本文将深入探讨 Docker 镜像预热的概念、必要性以及实现方法。通过详细的操作示例和实践建议,读者将了解如何有效地实现镜像预热,以加快容器启动速度,提高服务的响应能力。 Docker 镜像预热…

【代码】Processing笔触手写板笔刷代码合集

代码来源于openprocessing&#xff0c;考虑到国内不是很好访问&#xff0c;我把我找到的比较好的搬运过来&#xff01; 合集 参考&#xff1a;https://openprocessing.org/sketch/793375 https://github.com/SourceOf0-HTML/processing-p5.js/tree/master 这个可以体验6种笔触…

第十六篇【传奇开心果系列】Python的OpenCV库技术点案例示例:图像质量评估

传奇开心果短博文系列 系列短博文目录Python的OpenCV库技术点案例示例短博文系列博文目录前言一、图像质量评估方法和相关函数的介绍二、均方误差示例代码三、峰值信噪比示例代码四、结构相似性指数示例代码五、视频质量评估示例代码六、OpenCV均方根误差计算示例代码七、OpenC…

政安晨:快速学会~机器学习的Pandas数据技能(五)(分组和排序)

提升您的洞察力水平&#xff0c;数据集越复杂&#xff0c;这一点就越重要。 概述 映射允许我们逐个值地转换DataFrame或Series中的数据&#xff0c;针对整个列进行操作。然而&#xff0c;通常我们希望对数据进行分组&#xff0c;然后对所在组进行特定操作。 正如你将学到的&a…

十二、常见算法和Lambda——五道经典算法题

十二、常见算法和Lambda——经典算法题 练习一&#xff08;按照要求进行排序&#xff09;练习2:&#xff08;不死神兔&#xff09;练习3&#xff08;猴子吃桃子&#xff09;练习4&#xff08;爬楼梯&#xff09; 练习一&#xff08;按照要求进行排序&#xff09; 定义数组并存…