Mybatis在整个体系中的作用是负责连接并访问数据库层。搞过开发的同学都知道,没有数据库的项目一无是处,所以Mybatis的学习是很有必要的。提供本文章的demo仓库。
准备工作:
- 数据库:在进入正式学习前,先确保Mysql已经在电脑上安装好了,最好再安装一个可视化管理工具Navicat Premium for mysql。当然,你还要会mysql的语法和基本操作等。
- spring boot项目创建以及一些前置知识:可以看我上一篇博客
一、整合Mybatis
整合Mybatis可以基于注解,也可以基于xml文件,二者的区别:
1.搭建数据库环境
新建一个数据库boot_demo,然后执行以下sql语句:
-- 创建表
USE `boot_demo`;
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
`user_id` int(11) NOT NULL ,
`user_name` varchar(20) DEFAULT NULL,
`user_age` int(11) DEFAULT NULL,
PRIMARY KEY (`user_id`)
) ENGINE = InnoDB;
-- 插入数据
REPLACE INTO `tb_user` (`user_id`, `user_name`, `user_age`) VALUES ('100', 'test01', '100');
2.基于注解整合Mybatis
(1)创建项目
项目信息填写如下:
选择初始依赖:
完善目录结构:
在main/java/com/tracy/mybatisdemo下依次新建 entity 、dao 和 controller 文件夹。一般来说,应该再创建一个service包,前端调用controller接口,controller调用service,service再调用dao,但这章为了简化操作省去了service部分,到后面项目实战的时候我会创建更完善的目录结构。
(2)具体代码实现
- 实体类User:
在entity包下创建User类,代码如下:
package com.tracy.mybatisdemo.entity;
import lombok.Data;
//此注解来源于Lombok插件,运行时会自动为类添加 Getter、Setter 、有参构造、toString 、equals 和 hashCode 方法
@Data
public class User {
private Integer userId;
private String userName;
private Integer userAge;
}
- 持久层UserDao接口:
在dao包下创建UserDao接口:
package com.tracy.mybatisdemo.dao;
import com.tracy.mybatisdemo.entity.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserDao {
@Select("select user_id,user_name,user_age from tb_user")
List<User> findAll();
@Select("select user_id,user_name,user_age from tb_user where user_id = #{userId}")
User findById(Integer userId);
@Insert("insert into tb_user (user_id,user_name,user_age) values (#{userId},#{userName},#{userAge})")
Integer insert(User user);
@Update("update tb_user set user_name=#{userName},user_age=#{userAge} where user_id = #{userId}")
Integer update(User user);
@Delete("delete from tb_user where user_id=#{userId}")
Integer delete(Integer userId);
}
- 配置包扫描:
为了使每个dao接口都被扫描到,可以在每个dao接口上加上@Mapper注解,但当dao接口比较多的时候,推荐直接在启动类上通过注解@MapperScan("com.tracy.mybatisdemo.dao")
的形式扫描整个dao包:
@SpringBootApplication
@MapperScan("com.tracy.mybatisdemo.dao")
public class MybatisDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisDemoApplication.class, args);
}
}
- 控制层UserController类:
在controller包下创建UserController类:
package com.tracy.mybatisdemo.controller;
import com.tracy.mybatisdemo.dao.UserDao;
import com.tracy.mybatisdemo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserDao userDao;
@GetMapping("/findAll")
public List<User> findAll(){
return userDao.findAll();
}
@GetMapping("/findById")
public User findById(Integer userId){
return userDao.findById(userId);
}
@PostMapping("/insert")
public String insert(User user){
userDao.insert(user);
return "插入成功后的数据为" + userDao.findById(user.getUserId());
}
@PutMapping("/update")
public String update(User user){
userDao.update(user);
return "更新成功后的数据为" + userDao.findById(user.getUserId());
}
@DeleteMapping("/delete")
public String delete(Integer userId){
userDao.delete(userId);
return "删除成功的id" + userId;
}
}
- 添加数据库配置:
在application.yml中添加以下配置:
# 数据源
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/boot_demo?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
username: root
password: 你的密码
# Mybatis配置
# 开启驼峰式命名规则自动转换
mybatis:
configuration:
map-underscore-to-camel-case: true
(3)测试
测试工具我使用的是postman,怎么安装和使用可以网上百度一下。
- 测试 localhost:8080/user/findAll GET
- 测试 localhost:8080/user/findById GET
- 测试 localhost:8080/user/insert POST
- 测试 localhost:8080/user/update PUT
- 测试 localhost:8080/user/delete DELETE
成功!
3.基于xml整合Mybatis
基于注解的Mybatis使用只能应付一些比较简单的数据库查询语句,虽然省事,但在一定程度上也丧失了灵活性,因此,有必要学习一下基于xml整合Mybatis。
- 首先,请先删除UserDao接口中每个方法上的注解语句:
package com.tracy.mybatisdemo.dao;
import com.tracy.mybatisdemo.entity.User;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserDao {
List<User> findAll();
User findById(Integer userId);
Integer insert(User user);
Integer update(User user);
Integer delete(Integer userId);
}
- 添加xml映射文件:
在resources目录下创建目录mapper,仔仔mapper目录下创建UserMapper.xml文件:
注意 mapper namespace=“com.tracy.mybatisdemo.dao.UserDao” 一定要与dao包下的接口对应起来。
<?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">
<mapper namespace="com.tracy.mybatisdemo.dao.UserDao">
<!--查询所有用户-->
<select id="findAll" resultType="user">
select * from tb_user
</select>
<!--根据id查询单个用户-->
<select id="findById" parameterType="int" resultType="user">
select * from tb_user where user_id = #{
userId}
</select>
<!--插入用户-->
<insert id="insert" parameterType="user">
insert into tb_user (user_id,user_name,user_age) values (#{
userId},#{
userName},#{
userAge})
</insert>
<!--更新用户信息-->
<update id="update" parameterType="map">
update tb_user set user_name = #{
userName}, user_age = #{
userAge}
where user_id = #{
userId}
</update>
<!--删除用户-->
<delete id="delete" parameterType="int">
delete from tb_user where user_id = #{
userId}
</delete>
</mapper>
- 添加Mybatis实体映射配置:
在application.yml配置文件中增加mybatis部分的配置:
# Mybatis配置
# 开启驼峰式命名规则自动转换
mybatis:
configuration:
map-underscore-to-camel-case: true
type-aliases-package: com.tracy.mybatisdemo.entity
mapper-locations: classpath:mapper/*Mapper.xml
type-aliases-package: com.tracy.mybatisdemo.entity 表示将UserMapper.xml中的resultType与com.tracy.mybatisdemo.entity包下的实体类绑定起来,否则UserMapper.xml中的resultType需要写上完整的包名com.tracy.mybatisdemo.entity.user。
*mapper-locations: classpath:mapper/Mapper.xml 表示将dao路径下的各个接口与resources/mapper路径下的各个xml文件映射起来,classpath等价于resources目录。
- 测试:
前面已经演示过了,url和过程都是一模一样的,请用postman或者别的测试工具自行测试吧。
4.Mybatis的动态SQL
(1)if
if 在 where 子句中做简单的条件判断。
我们以UserMapper.xml中的update方法的实现为例:
- 原来的写法:
当我们调用这个接口时,必须把用户名、用户年龄参数都传入,也就是说我们必须修改每一个属性值。但是如果我们只想选择性地修改属性值呢,比如,有时候我们只想修改user_name,有时候又只想修改user_age。
<!--更新用户信息-->
<update id="update" parameterType="map">
update tb_user set user_name = #{
userName}, user_age = #{
userAge}
where user_id = #{
userId}
</update>
- 使用if进行动态SQL绑定:
我们为每个参数的传入加上一个if判断,test="user_name!=null"表明了它的判断条件,只有当该参数传入不为空时才进行修改,这就是一种动态绑定的策略。
<!--更新用户信息-->
<update id="update" parameterType="map">
update tb_user set user_id = #{
userId}
<if test="userName!=null">
user_name = #{
userName}
</if>
<if test="userAge!=null">
user_age = #{
userAge}
</if>
where user_id = #{
userId}
</update>
(2)choose
相当于java语言中的Switch语句。
- 仍以update方法为例:
每个when语句都是一个条件,第一个条件满足了就跳出choose语句,否则判断下一个when条件。如果所有的when条件都不满足,就直接选择otherwise中的条件。
<!--更新用户信息-->
<update id="update" parameterType="map">
update tb_user set
<choose>
<when test="userName!=null">
user_name = #{
userName}
</when>
<when test="userAge!=null">
user_age = #{
userAge}
</when>
<otherwise>
user_id = #{
userId}
</otherwise>
</choose>
where user_id = #{
userId}
</update>
(3)trim、where、set
- trim:
先来看看这个语句,如果两个if条件都不成立,那sql语句就会变成update tb_user set where user_id = #{userId},这就会导致语法上的错误:
<!--更新用户信息-->
<update id