当前位置: 首页 > news >正文

Web基础(六):Mybatis

目录

一、作用

二、环境准备

​三、XML无接口开发

四、Mapper接口开发

五、查询


一、作用

代替jdbc,解决jdbc的硬编码、繁杂代码问题

1. 硬编码(注册驱动,获取连接) -> mybatis-conf.xml

2. 繁杂代码(定义sql语句) -> XxxMapper.xml

二、环境准备

(一)三步走

1. maven配置

创建maven项目

设置 - 构建工具 - maven主路径、配置路径

2. pom.xml导入依赖

mybatis、mysql、junit、slf4j-api、logback-classic、logback-core

3. resource配置文件

mybatis核心配置、sql映射、logback配置

(二)mybatis核心配置文件

注意:核心配置文件标签要遵循MyBatis官网的结构顺序

1. 加载数据源,配置驱动信息、数据库连接信息

<environments default="默认数据源id"> <environment id="数据源id"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/数据库名?useSSL=false"/> <property name="username" value="用户名"/> <property name="password" value="密码"/> </dataSource> </environment> </environments>

2. 加载sql映射

(1)逐个加载映射:<mapper>resource属性,指定sql映射路径

(2)批量加载映射:<package>name属性,指定sql映射包全名

<!--1. 逐个加载映射--> <mappers> <mapper resource="com/liu/mybatis/mapper/XxxMapper.xml"/> </mappers> <!--2. 批量加载映射--> <mappers> <package name="com.liu.mybatis.mapper"/> </mappers>

3. 起类别名

<typeAliases> <typeAlias type="类全限定名" alias="类别名"/> </typeAliases>

(三)sql映射

1. 映射根配置:namespace 属性

作用:区分不同映射

(1) XML 无接口:自定义唯一名称,区分映射

(2) Mapper 接口:填写接口全类名,绑定接口

<!--1. XML无接口开发:自定义--> <mapper namespace="XxxMapper"> </mapper> <!--2. Mapper接口开发:接口全限定名--> <mapper namespace="com.liu.mybatis.mapper.XxxMapper"> </mapper>

2. sql声明标签

(1)标签类型:select/insert/update/delete

(2)属性:id,resultType / resultMap

注意:resultType和resultMap - type,填实体类的全限定名/别名

<!--1. resultType--> <select id="sqlID" resultType="结果集要封装成的目标实体类"> select * from tb_user </select> <!--2. resultMap--> <resultMap id="resultMapID" type="结果集要封装成的目标实体类"> <result column="字段名" property="字段别名"/> </resultMap> <select id="sqlID" resultMap="resultMapID"> </select>

3. sql内容编写

(1)参数占位符

① #{}:预编译占位符,防 SQL 注入,自动加引号

② ${}:字符串直接拼接,有注入风险,不加引号

(2)特殊字符处理

①转义字符:&lt; &gt; &amp;

②CDATA 区:<![CDATA[ 内容 ]]>

(3)模糊查询 like关键字
(4)动态 SQL 标签

①where:剔除开头多余 and/or;无查询条件时,不生成where语句

②if:条件成立,拼接 SQL

③choose:多条件单选,类似if-else if-else

<!--1. if标签--> select * from tb_brand <where> <if test="条件"></if> </where> <!--2. choose标签--> select * from tb_brand <where> <choose> <when test="条件"></when> <otherwise></otherwise> </choose> </where>

​三、XML无接口开发

(一)准备pojo,起类别名

(二)核心配置文件

(三)sql映射

(四)测试执行sql

1. 加载配置文件,获取SqlSessionFactory对象

(1)InputStream inputStream = Resources.getResourceAsStream(mybatis核心配置文件路径);

(2)SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

2. 获取SqlSession对象,用于执行sql

sqlSessionFactory.openSession()

3. 执行sql

sqlSession.selectList("namespace.sqlId")

4. 释放资源

sqlSession.close()

<?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"> <!--XML无接口开发:namespace为自定义--> <mapper namespace="UserMapper"> <select id="selectAll" resultType="com.liu.mybatis.pojo.User"> select * from tb_user </select> </mapper>
public class selectAll { public static void main(String[] args) throws IOException { //1. 加载核心配置文件,获取SqlSessionFactory对象 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2. 获取SqlSession对象,用于执行sql SqlSession sqlSession = sqlSessionFactory.openSession(); //3. 执行sql List<User> sl = sqlSession.selectList("UserMapper.selectAll"); System.out.println(sl); //4. 释放资源 sqlSession.close(); } }

四、Mapper接口开发

(一)准备pojo,起类别名

(二)Mapper接口

(三)sql映射

(四)执行sql

1. 加载配置文件,获取SqlSessionFactory对象

2. 获取SqlSession对象

3. 获取Mapper代理对象,用于执行sql

sqlSession.getMapper(XxxMapper.class)

4. 执行sql

xxxMapper.接口方法()

5. 释放资源

public interface BrandMapper { //返回值类型与sql封装类型对应:MyBatis根据接口返回值类型,自动封装sql查询结果。 //方法名与sql声明ID一致 List<Brand> selectAll(); }
<!--Mapper接口开发:namespace为接口全限定名--> <mapper namespace="com.liu.mybatis.mapper.BrandMapper"> <resultMap id="brandResultMap" type="Brand"> <result column="brand_name" property="brandName"/> <result column="company_name" property="companyName"/> </resultMap> <select id="selectAll" resultMap="brandResultMap"> select id,brand_name,company_name,ordered,description,status from tb_brand </select> </mapper>
@Test public void testSelectBrand() throws IOException { //1. 加载核心配置文件,获取SqlSessionFactory对象 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2. 获取SqlSession对象,用于执行sql SqlSession sqlSession = sqlSessionFactory.openSession(); //3. 获取UserMapper接口的代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); //4. 执行sql List<Brand> brands = brandMapper.selectAll(); System.out.println(brands); //5. 释放资源 sqlSession.close(); }

(五)同名规则

1. 接口与映射的名字、目录相同

2. 接口方法名与sql声明ID相同

3. 接口方法返回值类型与sql结果集要封装成的目标实体类对应

4. 传递参数:

(1)散装参数:散装参数名与sql占位符名称相同

(2)实体类参数:实体类属性名与sql占位符名称相同

(3)Map集合参数:键名与sql占位符名称相同

五、查询

1. 查询所有

2. 通过id查询

3. 多条件查询

4. 多条件动态查询

5. 单条件动态查询

http://www.jsqmd.com/news/860912/

相关文章:

  • MySQL事务与锁机制深度解析
  • 三角形的最小路径和---二维dp
  • 【Outbox 事件驱动 + Canal Binlog 增量订阅】:用户关系模块架构实战详解
  • 如何快速掌握《鸣潮》游戏模组开发:专业逆向工程与AES加密技术完整指南
  • DicomObjects COM -Release Date: 2026-05-18
  • minecraft-ondemand自动化运维:Watchdog容器原理与实现
  • 如何安全提取未知文件:unblob的5大安全防护机制实战指南
  • AALC自动化工具完整指南:如何用智能助手彻底优化《Limbus Company》游戏时间
  • 龙鱼缸设备怎么配不踩坑?灯光+水泵+滤材的搭配清单 - 华旭传媒
  • NCM文件转换终极指南:3步快速解密网易云音乐加密音频
  • 企业AI开发包含哪些内容:从需求分析到交付落地的完整指南 - 华旭传媒
  • MapReduce数据倾斜解决方案
  • gibMacOS终极指南:三步完成macOS组件下载与系统部署
  • 5分钟快速上手!网易云无损音乐下载完整指南:免费获取高品质音乐
  • Tunasync多数据库后端支持:Bolt、Badger、Redis、LevelDB对比分析
  • Magma高可用部署:如何构建企业级可靠网络基础设施
  • 重庆白发养黑理疗机构哪家好?黑奥秘牵头制定行业标准,专业服务更规范 - 美业信息观察
  • 【卷卷观察】Google I/O 2026 炸场:AI 不再跟你聊天了,它开始替你干活了
  • 3步搞定B站直播助手:新手主播的智能场控终极指南
  • 如何快速获取精准歌词?LDDC 跨平台歌词下载工具完整指南
  • TextShot快速入门:5分钟学会跨平台截图文字识别
  • Elog多平台支持对比:语雀、Notion、FlowUs、飞书哪个更适合你
  • 如何快速搭建家庭游戏串流服务器:Sunshine完整配置教程
  • Obsidian Full Calendar:在笔记中实现高效日程管理的完整指南
  • 瑞士ZuriQ研发新型彭宁离子阱处理器,大幅增强离子阱量子计算机计算能力
  • parse库自定义类型转换器开发指南:从简单函数到复杂模式匹配
  • Spark 安装与使用完全指南【保姆级教程】
  • 如何构建企业级无人机应用:DJI Android SDK V5架构设计与实战指南
  • 2026佛山搬家公司全攻略 大型工厂整体搬迁极简流程 - 从来都是英雄出少年
  • Navicat Premium Mac重置终极方案:3分钟恢复14天试用期