简单来说 MyBatis 是 更简单完成程序和数据库交互的 具 ,也就是更简单的操作和读取数据库工具。
开始搭建 MyBatis 之前,MyBatis 在整个框架中的定位,框架交互流程图:
MyBatis 也是一个 ORM 框架,ORM(Object Relational Mapping),即对象关系映射。在面向对象编程语 中, 将关系型数据库中的数据与对象建立起映射关系 ,进而自动的完成 数据与对象的互相转换 :
一般的 ORM 框架,会将数据库模型的每张表都映射为一个 Java 类。 也就是说使用 MyBatis 可以像操作对象 样来操作数据库中的表,可以实现对象和数据库表之间的转换。
-- 创建数据库drop database if exists mycnblog;create database mycnblog DEFAULT CHARACTER SET utf8mb4;-- 使用数据数据use mycnblog;-- 创建表[用户表]drop table if exists userinfo;create table userinfo( id int primary key auto_increment, username varchar(100) not null, password varchar(32) not null, photo varchar(500) default '', createtime datetime default now(), updatetime datetime default now(), `state` int default 1) default charset 'utf8mb4';-- 创建文章表drop table if exists articleinfo;create table articleinfo( id int primary key auto_increment, title varchar(100) not null, content text not null, createtime datetime default now(), updatetime datetime default now(), uid int not null, rcount int not null default 1, `state` int default 1)default charset 'utf8mb4';-- 创建视频表drop table if exists videoinfo;create table videoinfo( vid int primary key, `title` varchar(250), `url` varchar(1000),createtime datetime default now(),updatetime datetime default now(), uid int)default charset 'utf8mb4';
org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.4 mysql mysql-connector-java runtime
在 application.yml 配置数据库连接:
# 配置数据库连接spring: datasource: url: jdbc:mysql://127.0.0.1/mycnblog?charsetEncoding=utf8 username: root password: 12345678 driver-class-name: com.mysql.cj.jdbc.Driver
配置 MyBatis 中的 XML 路径:
# 设置Mybatis的xml保存路径mybatis: mapper-locations: classpath:mybatis/**Mapper.xml
按照后端开发的工程思路来实现 MyBatis 查询所有用户的功能:
目录结构:
添加用户的实体类:
@Setter@Getter@ToStringpublic class UserInfo { private int id; private String username; private String password; private String photo; private String createtime; private String updatetime; private int state;}
数据持久层的接口定义:
@Mapperpublic interface UserMapper { public List getAll(); }
数据持久层的实现,mybatis 的固定 xml 格式:
<?xml version="1.0" encoding="UTF-8"?>
UserMapper.xml 查询所有用户的具体实现 SQL:
<?xml version="1.0" encoding="UTF-8"?>
标签说明:
服务层实现代码如下:
@Servicepublic class UserService { @Resourceprivate UserMapper userMapper; public List getAll() { return userMapper.getAll(); } }
控制器层的实现代码如下:
@RestController@RequestMapping("/user")public class UserController { @Resource private UserService userService; @RequestMapping("/getuserbyid") public UserInfo getUserById(Integer id) { if (id != null && id > 0) { return userService.getUserById(id); } else { return new UserInfo(); } }}
① 添加 controller:
@RequestMapping("/insert") public Integer insert(UserInfo userInfo) { return userService.insert(userInfo); }
② 添加 service:
public Integer insert(UserInfo userInfo) { return userMapper.insert(userInfo); }
③ 添加 mapper :
Integer insert(UserInfo userInfo);
④ 添加 xml:
insert into userinfo(username,password,photo,state) values(#{username},#{password},#{photo},1)
特殊的增加
默认情况下返回的是受影响的行号,如果想要 返回自增 id ,具体实现如下:
controller 实现代码:
public Integer add2(@RequestBody UserInfo userInfo) { userService.getAdd2(userInfo); return user.getId();}
mapper 接口:
@Mapperpublic interface UserMapper { // 添加,返回 增id void add2(User user);}
mapper.xml 实现如下:
insert into userinfo(username,password,photo,state) values(#{username},#{password},#{photo},1)
useGeneratedKeyskeyColumnkeyProperty
前面三个步骤操作类似,重点看下第四步,数据持久层的实现(xml)。
delete from userinfo where id=#{id}
update userinfo set username=#{name} where id=#{id}
查询操作需要设置返回类型,绝大数查询场景可以使 resultType 进行返回,它的优点是使用方便,直接定义到某个实体类即可。
但有些场景就需要用到返回字典映射( resultMap )比如:
xml 如下:
② 一对一映射
一对一映射要使用 标签,具体实现如下(一篇文章只对应一个作者):
③ 一对多映射
一对多需要使用
like 使用 #{} 会报错,可以考虑使用 mysql 的内置函数 concat() 来处理,实现代码如下:
动态 sql 是Mybatis的强大特性之一,能够完成不同条件下不同的 sql 拼接。
可以参考官方文档: Mybatis动态sql
insert into userinfo(username, photo, password) values (#{username}, #{photo}, #{password})
test中的对象是传入对象的属性,当它不为空时,才拼接里面的内容。
prefixsuffixprefixOverridessuffixOverrides
示例:
insert into userinfo username, photo, password values #{username}, #{photo}, #{password}
传入的用户对象,根据属性做where条件查询,用户对象中属性不为 null 的,都为查询条件。
更新的时候也会出现问题, 使用
update userinfo username=#{username}, password=#{password} where id=#{id}
对集合进行遍历时可以使用该标签。标签有如下属性:
collectionitemopencloseseparator
示例:
delete from userinfo where id in #{id}
页面更新:2024-05-08
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号