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

快速搭建并学会使用Mybatis!!

文章目录

    • Mybatis是什么
  • 1、Mybatis环境搭建 && 测试案例
  • 2、Mybatis核心配置
  • 3、resultMap字段映射
  • 4、获取主键值
  • 5、抽取公共字段
  • 6、参数处理
    • 面试知识点,#{}与${}的区别:
  • 7、动态sql

Mybatis是什么

Mybatis是一款优秀的持久层框架,用于简化JDBC开发。

Mybatis官方文档链接:
Mybatis官方文档

1、Mybatis环境搭建 && 测试案例

开发环境:jdk17 + idea2022 + maven 3.8.1

创建数据库:

create database mybatis;
use mybatis;drop table if exists tb_user;create table tb_user(id int primary key auto_increment,user_name varchar(20),password varchar(20),gender char(1),addr varchar(30)
);INSERT INTO tb_user VALUES (1, 'zhangsan', '123', '男', '北京');
INSERT INTO tb_user VALUES (2, '李四', '234', '女', '天津');
INSERT INTO tb_user VALUES (3, '王五', '11', '男', '重庆');

创建项目:
在这里插入图片描述
导入maven的 pom.xml 依赖:

	<dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.10</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.23</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version></dependency><!-- junit单元测试 --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><!-- 添加slf4j日志api --><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.20</version></dependency><!-- 添加logback-classic依赖 --><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-classic</artifactId><version>1.2.3</version></dependency><!-- 添加logback-core依赖 --><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-core</artifactId><version>1.2.3</version></dependency></dependencies>

resource目录下添加配置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><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql:///mybatis?userSSL=false"/><property name="username" value="root"/><property name="password" value="root"/></dataSource></environment></environments><mappers><!-- 加载sql映射文件 --><mapper resource="org/mybatis/example/BlogMapper.xml"/></mappers>
</configuration>

创建User实体类,映射数据库:

public class User {private Integer id;private String userName;private String password;private String gender;private String addr;// 省略setter、getter、构造、toString等方法
}

项目结构:
在这里插入图片描述
UserMapper接口:

public interface UserMapper {User getUserById(Integer id);List<User> getAllUser();
}

UserMapper.xml映射文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis.mapper.UserMapper"><select id="getUserById" resultType="com.mybatis.po.User">select id, user_name as userName, password, gender, addr from tb_user where id = #{id}</select><select id="getAllUser" resultType="com.mybatis.po.User">select id, user_name as userName, password, gender, addr from tb_user</select><insert id="insert">insert into tb_user (id,user_name, password, gender, addr)values(#{id}, #{userName}, #{password}, #{gender}, #{addr});</insert>
</mapper>

其中mapper标签的namespace字段传入的是UserMapper全限定类名,即包含包前缀

以select字段举例,id就是方法名,resultType就是返回类型的全限定类名。

MybatisDemo测试:

public static void main(String[] args) {// 1.构建SqlSessionFactoryInputStream is = null;try {is = Resources.getResourceAsStream("mybatis-config.xml");} catch (IOException e) {throw new RuntimeException(e);}SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);// 2.从sqlSessionFactory中获取sqlSession(打开会话)SqlSession sqlSession = sqlSessionFactory.openSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);// 3.获取用户列表,User user = mapper.getUserById(1);System.out.println(user);List<User> allUser = mapper.getAllUser();for (User user1 : allUser) {System.out.println(user1);}User user = new User();user.setUserName("mybatis");user.setGender("男");user.setPassword("123456");user.setAddr("idea");Integer i = mapper.insert(user);System.out.println(i);//新增操作需要手动提交sqlSession.commit();}

运行结果:

User{id=1, userName='zhangsan', password='123', gender='男', addr='北京'}
User{id=1, userName='zhangsan', password='123', gender='男', addr='北京'}
User{id=2, userName='李四', password='234', gender='女', addr='天津'}
User{id=3, userName='王五', password='11', gender='男', addr='重庆'}
1

这样,我们就成功配置并跑通测试了一个Mybatis案例。

2、Mybatis核心配置

properties配置 :
mybaits-config.xml更改添加配置:

<properties><property name="dbUserName" value="root"/><property name="dbPassword" value="root"/><property name="dbDriver" value="com.mysql.cj.jdbc.Driver"/><property name="dbUrl" value="jdbc:mysql:///mybatis?userSSL=false"/></properties><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="${dbDriver}"/><property name="url" value="${dbUrl}"/><property name="username" value="${dbUserName}"/><property name="password" value="${dbPassword}"/></dataSource></environment></environments>

简单来说,其实就是将原本environments配置项中的property参数替换成了。
prepertys中配置的各属性,这样方便修改,进行了解耦操作。

typeAlias别名:
在这里插入图片描述

映射器:

在这里插入图片描述
其余配置可去官网查阅。

3、resultMap字段映射

这里主要是resultMap的使用,涉及数据库中蛇形命名字段和实体类中的驼峰命名字段的映射。

修改UserMapper.xml:

    <resultMap id="userMap" type="com.mybatis.po.User"><result column="user_name" property="userName"/></resultMap><select id="getUserById" resultMap="userMap">select id, user_name, password, gender, addr from tb_user where id = #{id}</select><select id="getAllUser" resultMap="userMap">select id, user_name , password, gender, addr from tb_user</select>

resultMap的作用就是将数据库的column字段映射到java对象的property字段。

4、获取主键值

一般我们在插入操作之后,字段会有一个自增id,我们想要获取其值的话需要映射文件进行如下设置。
UserMapper.xml:

	<insert id="insert" useGeneratedKeys="true" keyProperty="id">insert into tb_user (id,user_name, password, gender, addr)values(#{id}, #{userName}, #{password}, #{gender}, #{addr});</insert>

keyProperty表明主键字段名是什么,useGeneratedKeys = true如果想获取主键就要开启。
测试代码:

		User user = new User();user.setUserName("mybatis02");user.setGender("男");user.setPassword("123456");user.setAddr("idea");Integer i = mapper.insert(user);System.out.println("主键值为:" + user.getId());//新增操作需要手动提交sqlSession.commit();

运行结果:

6

5、抽取公共字段

修改UserMapper.xml:

	<sql id="baseColumn">id, user_name, password, gender, addr</sql><select id="getUserById" resultMap="userMap" >select <include refid="baseColumn"/> from tb_user where id = #{id}</select><select id="getAllUser" resultMap="userMap">select <include refid="baseColumn"/> from tb_user</select>

6、参数处理

主要是一个@Param注解
UserMapper添加方法:

List<User> findUserByCondition(@Param("id") Integer id, @Param("gender") String gender);

UserMapper.xml:

<select id="findUserByCondition" resultType="com.mybatis.po.User">select <include refid="baseColumn"/> from tb_userwhere gender = #{gender} and id = #{id}</select>

我们只需要清楚,@Param()里面设置的参数名是什么,我们在sql语句中使用的时候,#{}里面就写什么。

面试知识点,#{}与${}的区别:

#{}: 预编译处理,防止 SQL 注入,使用占位符 ?,值作为参数传递,适用于动态值。
${}: 直接字符串替换,未预编译,可能导致 SQL 注入,适用于表名、列名等非动态值。

简单来说,就是#{}会给你传进来的参数值上面加一个 ’ ‘,而 不会, {}不会, 不会,{}适合需要动态指定表名的时候使用,因为表名不能加’ ', 而且只能使用这个。

7、动态sql

如图,常用的其实也就是if和foreach标签,可以理解为java中的if和for循环语句。
UserMapper.xml:

<select id="findUserByCondition" resultType="com.mybatis.po.User">select <include refid="baseColumn"/> from tb_userwhere<if test="gender != null and gender != ''">gender = #{gender}</if><!--foreach可以对集合进行循环,加入ids是传进来的一个id集合,像是我们java中for循环遍历--><!-- open表示从什么开始,close表示用什么结束,separator表示用什么分割参数,item表示形参名 -->and id in<foreach collection="ids" item="temId" open="(" close=")" separator=",">#{temId}</foreach></select>

深入学习可点击文章最开始去Mybatis3官网学习。

相关文章:

  • Linux中进程的属性:进程优先级
  • Pytorch-CUDA版本环境配置
  • The Traitor King (10 player 25 player)
  • 哈希函数详解(SHA-2系列、SHA-3系列、SM3国密)案例:构建简单的区块链——密码学基础
  • 游戏引擎学习第256天:XBox 控制器卡顿和修复 GL Blit 伽玛问题
  • 数据分析与可视化实战:从鸢尾花到乳腺癌数据集
  • AI日报 · 2025年5月03日|Perplexity 集成 WhatsApp,苹果传与 Anthropic 合作开发 Xcode
  • list类的详细讲解
  • day13 python不平衡数据集的处理(补)
  • 类与类之间的关系详解
  • InnoDB索引的原理
  • 实验二 软件白盒测试
  • 状压 DP 详解
  • 一种快速计算OTA PSRR的方法(Ⅰ)
  • 前端面经-VUE3篇--vue3基础知识(二)计算属性(computed)、监听属性(Watch)
  • 双指针(5)——有效三角形个数
  • 头皮理疗预约小程序开发实战指南
  • 大模型开发学习笔记
  • Java 自旋锁:实现机制与优化策略
  • 【Bootstrap V4系列】学习入门教程之 表格(Tables)和画像(Figure)
  • 郑州一街道被指摊贩混乱经营,12345热线:已整治并加强巡查
  • 《中国医药指南》就涉宫颈癌等论文出现男性病例致歉:辞退涉事编辑
  • 罗马尼亚临时总统博洛让任命普雷多尤为看守政府总理
  • 牛市早报|“五一”假期预计跨区域人员流动量累计14.67亿人次
  • 科普|治疗腰椎间盘突出症,筋骨平衡理论如何提供新视角?
  • 这样喝酸奶相当于在喝糖水,会导致娃龋齿、肥胖