网站首页 > 博客文章 正文
一、简介
1.1 MyBatis介绍
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC代码和手动设置参数以及获取结果集。
1.2 MyBatis发展史
MyBatis 原本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis ,2013年11月迁移到Github。
1.3 MyBatis和Hibernate的区别
MyBatis 和 Hibernate 都是优秀的持久化框架,都支持JDBC(Java DataBase Connection)和JTA(Java Transaction API)事务处理。
MyBatis 优点
- 更加轻量级,如果说Hibernate是全自动的框架,MyBatis就是半自动的框架;
- 入门简单,即学即用,并且延续了很好的SQL使用经验;
Hibernate 优点
- 开发简单、高效,不需要编写SQL就可以进行基础的数据库操作;
- 可移植行好,大大降低了MySQL和Oracle之间切换的成本(因为使用了HQL查询,而不是直接写SQL语句);
- 缓存机制上Hibernate也好于MyBatis;
1.4 MyBatis集成方式
Mybatis集成方式分为两种:
- 注解版集成
- XML版本集成
XML版本为老式的配置集成方式,重度集成XML文件,SQL语句也是全部写在XML中的;注解版版本,相对来说比较简约,不需要XML配置,只需要使用注解和代码来操作数据。
二、注解版 MyBatis 集成
开发环境
- MySQL 8.0.12
- Spring Boot 2.0.4
- MyBatis Spring Boot 1.3.2(等于 MyBatis 3.4.6)
- JDK 8
- IDEA 2018.2
MyBatis Spring Boot 是 MyBatis 官方为了集成 Spring Boot 而推出的MyBatis版本。
2.1 添加依赖
设置pom.xml文件,添加如下配置
体验AI代码助手
代码解读
复制代码
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.12</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency>
添加 MySQL 和 MyBatis 支持。
2.2 配置数据库连接
设置application.properties文件,添加如下配置
体验AI代码助手
代码解读
复制代码
# MyBatis 配置 spring.datasource.url=
jdbc:mysql://172.16.10.79:3306/mytestdb?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.type-aliases-package=
com.hello.springboot.mapper
- spring.datasource.url 数据库连接字符串
- spring.datasource.username 数据库用户名
- spring.datasource.password 数据库密码
- spring.datasource.driver-class-name 驱动类型(注意MySQL 8.0的值是com.mysql.cj.jdbc.Driver和之前不同)
- mybatis.type-aliases-package 配置mapper包名
Mapper文件说明
Mapper是MyBatis的核心,是SQL存储的地方,也是配置数据库映射的地方。
2.3 设置 MapperScan 包路径
直接在启动文件
SpringbootApplication.java的类上配置@MapperScan,这样就可以省去,单独给每个Mapper上标识@Mapper的麻烦。
体验AI代码助手
代码解读
复制代码
@SpringBootApplication @MapperScan("com.hello.springboot.mapper") public class SpringbootApplication { public static void main(String[] args) { SpringApplication.run(SpringbootApplication.class, args); } }
2.4 添加代码
为了演示的简洁性,我们不做太多的分层处理了,我们这里就分为:实体类、Mapper接口、Controller类,使用Controller直接调用Mapper接口进行数据持久化处理。
User 类:
体验AI代码助手
代码解读
复制代码
public class User { private Long id; private String name; private int age; private String pwd; //省去set、get方法 }
UserMapper 接口:
体验AI代码助手
代码解读
复制代码
public interface UserMapper { @Select("select * from user") @Results({ @Result(property = "name", column = "name") }) List<User> getAll(); @Select("select * from user where id=#{id}") User getById(Long id); @Insert({"insert into user(name,age,pwd) values(#{name},#{age},#{pwd})"}) void install(User user); @Update({"update user set name=#{name} where id=#{id}"}) void Update(User user); @Delete("delete from user where id=#{id}") void delete(Long id); }
可以看出来,所有的SQL都是写在Mapper接口里面的。
Mapper里的注解说明
- @Select 查询注解
- @Result 结果集标识,用来对应数据库列名的,如果实体类属性和数据库属性名保持一致,可以忽略此参数
- @Insert 插入注解
- @Update 修改注解
- @Delete 删除注解
Controller 控制器:
体验AI代码助手
代码解读
复制代码
@RestController @RequestMapping("/") public class UserController { @Autowired private UserMapper userMapper; @RequestMapping("/") public ModelAndView index() { User user = new User(); user.setAge(18); user.setName("Adam"); user.setPwd("123456"); userMapper.install(user); ModelAndView modelAndView = new ModelAndView("/index"); modelAndView.addObject("count", userMapper.getAll().size()); return modelAndView; } }
到此为止,已经完成了MyBatis项目的配置了,可以运行调试了。
注解版GitHub源码下载:github.com/vipstone/sp…
三、XML 版 MyBatis 集成
3.1 添加依赖
设置pom.xml文件,添加如下配置
体验AI代码助手
代码解读
复制代码
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.12</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency>
添加 MySQL 和 MyBatis 支持。
3.2 配置数据库连接
设置application.properties文件,添加如下配置
体验AI代码助手
代码解读
复制代码
# MyBatis 配置 spring.datasource.url=
jdbc:mysql://172.16.10.79:3306/mytestdb?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.type-aliases-package=
com.hello.springboot.entity mybatis.config-locations=
classpath:mybatis/mybatis-config.xml mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
- spring.datasource.url 数据库连接字符串
- spring.datasource.username 数据库用户名
- spring.datasource.password 数据库密码
- spring.datasource.driver-class-name 驱动类型(注意MySQL 8.0的值是com.mysql.cj.jdbc.Driver和之前不同)
- mybatis.type-aliases-package 实体类包路径
- mybatis.config-locations 配置MyBatis基础属性
- mybatis.mapper-locations 配置Mapper XML文件
3.3 设置 MapperScan 包路径
直接在启动文件
SpringbootApplication.java的类上配置@MapperScan,这样就可以省去,单独给每个Mapper上标识@Mapper的麻烦。
体验AI代码助手
代码解读
复制代码
@SpringBootApplication @MapperScan("com.hello.springboot.mapper") public class SpringbootApplication { public static void main(String[] args) { SpringApplication.run(SpringbootApplication.class, args); } }
3.4 配置XML文件
本示例设置两个xml文件,在resource/mybatis下的mybatis-config.xml(配置MyBatis基础属性)和在resource/mybatis/mapper下的UserMapper.xml(用户和数据交互的SQL语句)。
mybatis-config.xml
体验AI代码助手
代码解读
复制代码
<?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> <typeAliases> <typeAlias alias="Integer" type="java.lang.Integer"/> <typeAlias alias="Long" type="java.lang.Long"/> <typeAlias alias="HashMap" type="java.util.HashMap"/> <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap"/> <typeAlias alias="ArrayList" type="java.util.ArrayList"/> <typeAlias alias="LinkedList" type="java.util.LinkedList"/> </typeAliases> </configuration>
UserMapper.xml
体验AI代码助手
代码解读
复制代码
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "
http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--namespace是命名空间,是mapper接口的全路径--> <mapper namespace="
com.hello.springboot.mapper.UserMapper"> <!--resultMap – 是最复杂也是最强大的元素,用来描述如何从数据库结果集中来加载对象--> <resultMap id="userResultMap" type="
com.hello.springboot.entity.User"> <id property="name" column="username"></id> </resultMap> <!--sql – 可被其他语句引用的可重用语句块--> <sql id="colums"> id,username,age,pwd </sql> <select id="findAll" resultMap="userResultMap"> select <include refid="colums" /> from user </select> <select id="findById" resultMap="userResultMap"> select <include refid="colums" /> from user where id=#{id} </select> <insert id="insert" parameterType="
com.hello.springboot.entity.User" > INSERT INTO user (username,age,pwd) VALUES (#{name}, #{age}, #{pwd}) </insert> <update id="update" parameterType="
com.hello.springboot.entity.User" > UPDATE users SET <if test="username != null">username = #{username},</if> <if test="pwd != null">pwd = #{pwd},</if> username = #{username} WHERE id = #{id} </update> <delete id="delete" parameterType="java.lang.Long" > DELETE FROM user WHERE id =#{id} </delete> </mapper>
SQL 映射文件有很少的几个顶级元素(按照它们应该被定义的顺序):
- cache – 给定命名空间的缓存配置。
- cache-ref – 其他命名空间缓存配置的引用。
- resultMap – 是最复杂也是最强大的元素,用来描述如何从数据库结果集中来加载对象。
- parameterMap – 已废弃!老式风格的参数映射。内联参数是首选,这个元素可能在将来被移除,这里不会记录。
- sql – 可被其他语句引用的可重用语句块。
- insert – 映射插入语句
- update – 映射更新语句
- delete – 映射删除语句
- select – 映射查询语句
注意: MyBatis中 config 和 mapper 的 XML 头文件是不一样的。
config 头文件
体验AI代码助手
代码解读
复制代码
<?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">
mapper 头文件
体验AI代码助手
代码解读
复制代码
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
Mapper XML 更多配置:
www.mybatis.org/mybatis-3/z…
3.5 添加代码
为了演示的便捷性,我们添加3个类用于功能的展示,分别是实体类User.java、mapper接口UserMapper.java和控制器类UserController.java,使用控制器类直接调用UserMapper的方法,进行数据存储和查询。
User.java
体验AI代码助手
代码解读
复制代码
package
com.hello.springboot.entity; public class User { private Long id; private String name; private int age; private String pwd; //省略set/get方法 }
UserMapper.java
体验AI代码助手
代码解读
复制代码
package com.hello.springboot.mapper; import com.hello.springboot.entity.User; import java.util.List; public interface UserMapper { List<User> findAll(); User findById(Long id); void insert(User user); void update(User user); void delete(Long id); }
注意: Mapper里的方法名必须和Mapper XML里的一致,不然会找不到执行的SQL。
UserController.java
体验AI代码助手
代码解读
复制代码
@RestController @RequestMapping("/") public class UserController { @Resource private UserMapper userMapper; @RequestMapping("/") public ModelAndView index() { User user = new User(); user.setAge(18); user.setName("Adam"); user.setPwd("123456"); userMapper.insert(user); ModelAndView modelAndView = new ModelAndView("/index"); modelAndView.addObject("count", userMapper.findAll().size()); return modelAndView; } }
到此为止,已经完成了MyBatis项目的配置了,可以运行调试了。
XML版GitHub源码下载:github.com/vipstone/sp…
四、总结
到目前为止我们已经掌握了MyBatis的两种集成方式,注解集成和XML集成,注解版更符合程序员的代码书写习惯,适用于简单快速查询;XML版可以灵活的动态调整SQL,更适合大型项目开发,具体的选择还要看开发场景以及个人喜好了。
猜你喜欢
- 2025-07-17 你没见过的分库分表原理解析和解决方案(二)
- 2025-07-17 安装MySQL(绿联nas安装mysql)
- 2025-07-17 SpringBoot数据库管理 - 用Liquibase对数据库管理和迁移?
- 2025-07-17 一个轻量级 Java 权限认证框架,Sa-Token 让鉴权变得简单、优雅!
- 2025-07-17 高效使用Java构建工具,Maven篇|云效工程师指北
- 2025-07-17 Java,screw,生成简洁好用的数据库表结构(html、doc、md)文档
- 2025-07-17 SpringBoot数据库操作的应用(springboot如何操作数据库)
- 2025-07-17 Mac Docker环境,利用Canal实现MySQL同步ES
- 2025-07-17 经常使用到开源的MySQL,今天我们就来系统地认识一下
- 2025-07-17 用 Spring AI Alibaba 开发了一款能连接 MySQL 的 MCP 服务,手把手教你
你 发表评论:
欢迎- 08-06nginx 反向代理
- 08-06跨表插入连续的日期,sheetsname函数#excel技巧
- 08-06初中生也能学的编程,不走弯路,先用后学
- 08-06find命令的“七种武器”:远不止-name和-type
- 08-06恶意代码常见的编程方式
- 08-06kali2021ping 外网不通
- 08-06因为一个函数strtok踩坑,我被老工程师无情嘲笑了
- 08-06hadoop集群搭建详细方法
- 23℃nginx 反向代理
- 最近发表
- 标签列表
-
- ifneq (61)
- 字符串长度在线 (61)
- googlecloud (64)
- powershellfor (73)
- messagesource (71)
- plsql64位 (73)
- vueproxytable (64)
- npminstallsave (63)
- #NAME? (61)
- promise.race (63)
- 2019cad序列号和密钥激活码 (62)
- window.performance (66)
- qt删除文件夹 (72)
- mysqlcaching_sha2_password (64)
- nacos启动失败 (64)
- ssh-add (70)
- yarnnode (62)
- abstractqueuedsynchronizer (64)
- source~/.bashrc没有那个文件或目录 (65)
- springboot整合activiti工作流 (70)
- jmeter插件下载 (61)
- 抓包分析 (60)
- idea创建mavenweb项目 (65)
- qcombobox样式表 (68)
- pastemac (61)
本文暂时没有评论,来添加一个吧(●'◡'●)