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

Mybatis框架

一、Mybatis简介:

        1、 Jdbc操作数据库存在的问题

                频繁创建和打开、关闭数据连接,太消耗资源

                Sql语句存在硬编码,不利于维护

                Sql参数设置硬编码,不利于维护

                结果集获取与遍历复杂,存在硬编码,不利于维护,期望能够查询后返回一个java对象

        2、 Myabtis简介

                MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis ,2013年11月迁移到Github。

                Mybatis是面向sql的持久层框架,他封装了jdbc访问数据库的过程,我们开发,只需专注于sql语句本身的拼装,其它复杂的过程全部可以交给mybatis去完成。

                Mybatis将传统的jdbc的硬伤都解决了,复杂的传参、结果集处理、sql于接口代码的强耦合、及连接问题全部由mybatis封装自动完成,程序员只需要简单对应的配置映射文件即可,极大简化了持久层的开发过程!

                Github:Releases · mybatis/mybatis-3 · GitHub

                中文文档:https://mybatis.org/mybatis-3/zh/index.html

二、Mybatis的入门程序

        1、入门程序的搭建流程

                1、建maven项目
                2、引入依赖jar坐标
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.wu</groupId><artifactId>maven</artifactId><version>1.0-SNAPSHOT</version><dependencies><!--mybatis--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.13</version></dependency><!--mysql--><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><version>8.0.31</version></dependency><!--测试jar--><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter</artifactId><version>RELEASE</version><scope>compile</scope></dependency></dependencies></project>
               3、在resources下写数据源配置文件(db.properties)
driver=com.mysql.cj.jdbc.Driver
user=root
pwd=root
url=jdbc:mysql://127.0.0.1:3306/stu
                 4、在resources下写Mybatis核心配置文件 (mybatis-config.xml)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!--加载  db.properties 到内存中 --><properties resource="db.properties"></properties><!--配置连接环境--><environments default="dev"><environment id="dev"><transactionManager type="JDBC"></transactionManager><!--<dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="username" value="root"/><property name="password" value="123456"/><property name="url"value="jdbc:mysql://127.0.0.1:3306/stu?serverTimezone=Asia/Shanghai"/></dataSource>--><dataSource type="POOLED"><property name="driver" value="${driver}"/><property name="username" value="${user}"/><property name="password" value="${pwd}"/><property name="url" value="${url}"/></dataSource></environment></environments><!--读取加载 GoodsDao.xml 文件--><mappers><mapper resource="StudentDao.xml"></mapper></mappers>
</configuration>
                5、 创建一个与数据库对应的实体类对象(student)

 

                 6、在dao包下创建一个接口

                7、在resources下创建一个与dao层对应的接口名字后缀为xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wu.dao.StudentDao"><!--查询所有学生--><select id="selectList" resultType="com.wu.entity.Student">select * from student</select><!--条件查询姓名--><select id="selectByName" resultType="com.wu.entity.Student">select * from student where name = #{name}</select><!--查询年龄大于--><!--&lt  <(小于) --> <!--&gt >(大于) --> <!--&lt;=  <=(小于等于) --><select id="selectByAge" resultType="com.wu.entity.Student">select * from student where age  &lt; #{age}</select><!--查询班级和年龄--><select id="selectByBjAge" resultType="com.wu.entity.Student">select * from student where bj = #{bj} and age = #{age}</select><!--模糊查询--> <!--不能用字符拼接 要用拼接函数concat()--><select id="selectLikeName" resultType="com.wu.entity.Student">select * from student where name like concat("%",#{nmae},"%")</select>
</mapper>
                8、在service包下创建一个类测试是否能查询到数据库数据
public class UserService {@Testpublic void test1() throws IOException {//加载mybatis的配置文件到内存中InputStream resource = Resources.getResourceAsStream("mybatis-config.xml");//创建连接工厂SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resource);//通过连接工厂创建连接对象SqlSession session = factory.openSession();//执行sql语句List<Student> list = session.selectList("com.wu.dao.StudentDao.selectList");//打印结果list.forEach(System.out::println);}@Testpublic void test2() throws IOException {//加载mybatis的配置文件到内存InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");//创建连接工厂SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);//通过连接工厂创建连接对象SqlSession session = factory.openSession();//获取dao接口 mybatis会动态代理去根据对应的xml文件创建实现StudentDao mapper = session.getMapper(StudentDao.class);//调用接口中的方法List<Student> list = mapper.selectList();//打印结果list.forEach(System.out::println);//提交事务//session.commit();//关闭事务session.close();}
}

        注意:每次都需要加载mybatis配置文件和创建工厂所有我们可以提前出来创建一个工具类

                9、在utils包下创建一个工具类(MybatisUtils)
package com.wu.utils;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 java.io.IOException;
import java.io.InputStream;/*** @author 86136*/
public class MybatisUtils {private static SqlSessionFactory factory;//静态代码块 加载配置 创建连接工厂static {InputStream inputStream = null;try {inputStream = Resources.getResourceAsStream("mybatis-config.xml");factory = new SqlSessionFactoryBuilder().build(inputStream);} catch (IOException e) {e.printStackTrace();}}//获取连接对象public static SqlSession getSqlSession() {return factory.openSession();}
}
                10、调用工具类来连接对象
package com.wu.Service;
import com.wu.dao.StudentDao;
import com.wu.entity.Student;
import com.wu.utils.MybatisUtils;
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 org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;/*** @author 86136*/
public class UserService {@Testpublic void test3() throws IOException {SqlSession session = MybatisUtils.getSqlSession();StudentDao dao = session.getMapper(StudentDao.class);List<Student> list = dao.selectList();list.forEach(System.err::println);}

http://www.xdnf.cn/news/659053.html

相关文章:

  • Redis分布式缓存核心架构全解析:持久化、高可用与分片实战
  • UDP协议原理与Java编程实战:无连接通信的奥秘
  • 【Webtrees 手册】第 4 章 - 编辑指南
  • 通用的管理账号设置设计(一)
  • 02. [Python+Golang+PHP]三数之和,多种语言实现最优解demo
  • 华为OD机试真题——分糖果(2025A卷:100分)Java/python/JavaScript/C/C++/GO最佳实现
  • Linux 网络配置现代实践:Netplan 与 ifcfg 的全景对比与工程指南20250526
  • 身份证二要素核验:数字经济时代的信任基石
  • React从基础入门到高级实战:React 核心技术 - 表单处理与验证深度指南
  • 关于模型记忆力的实现方式
  • Linux GPIO子系统深度解析:从历史演进到实战应用
  • 使用 Pfam 和 InterProScan 进行蛋白质家族和功能域的分析
  • 第一章:MLOps/LLMOps 导论:原则、生命周期与挑战
  • 激光开卷落料线:技术革新与产业应用综述
  • PCCW Global 与银河航天在港成功完成低轨卫星测试
  • 紫光同创FPGA实现视频采集转USB2.0输出,基于CY7C68013芯片,提供PDS工程源码和技术支持和QT上位机
  • DC-DC升压
  • 【Qt】Debug版本正常运行,Release版本运行卡死
  • FreeRTOS 事件标志组详解:原理、用法与实战技巧
  • 网页模板素材网站 web前端网页制作模板
  • 如何清除浏览器启动hao点360
  • 【多智能体系统开发框架AutoGen解析与实践】
  • 初学ADC
  • 【四】频率域滤波(下)【830数字图像处理】
  • 华为OD机试真题——通信系统策略调度(用户调度问题)(2025B卷:100分)Java/python/JavaScript/C/C++/GO最佳实现
  • 算力服务器和GPU服务器之间的联系
  • C++中使用类的继承机制来定义和实现基类与派生类
  • 初始化硬盘时,选MBR还是GUID?—「小白教程」
  • Linux系统中为Qt项目封装一个udp客户端类
  • 在麒麟系统(Kylin OS)上安装`geckodriver`