重新建立一个SpringBoot工程

选择依赖组件

然后删除不需要的Maven&Git文件

还是先查看我们的POM文件

整合Mybatis的组件多了这一个,默认的版本是3.5.4

然后再看看整个Mybatis整合的体系

创建数据库信息:

部门表:

CREATE TABLE `t_department` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`department_name` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8

职员表

CREATE TABLE `t_employee` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`last_name` varchar(10) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`gender` int DEFAULT NULL,
`department_id` int unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_emp_dp_dpid` (`department_id`),
CONSTRAINT `fk_emp_dp_dpid` FOREIGN KEY (`department_id`) REFERENCES `t_department` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8

添加外键关联:【每次都会不可绑定,因为一些约束没有一致,要仔细找找】

ALTER TABLE table_name
ADD CONSTRAINT fk_table1_table2
FOREIGN KEY (column_name)
REFERENCES table2(column_name);

然后编写我们的数据源配置信息【用的默认Hikari】

spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql:///mybatis?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8
username: root
password: 123456

编写ORM实体类

部门类

package cn.dai.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.ibatis.type.Alias; /**
* @author ArkD42
* @file SpringBoot with Mybatis
* @create 2020 - 05 - 31 - 22:43
*/ @Alias("department")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Department { private Integer id;
private String department_name;
}

然后是职员类

package cn.dai.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.ibatis.type.Alias; /**
* @author ArkD42
* @file SpringBoot with Mybatis
* @create 2020 - 05 - 31 - 22:40
*/ @Alias("employee")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee { private Integer id;
private String last_name;
private String email;
private Integer gender;
private Integer department_id; }

1、【使用全注解完成映射配置】

编写映射接口

package cn.dai.mapper;

import cn.dai.pojo.Department;
import org.apache.ibatis.annotations.*; import java.util.List; /**
* @author ArkD42
* @file SpringBoot with Mybatis
* @create 2020 - 05 - 31 - 22:46
*/ @Mapper //指定这是映射接口
public interface DepartmentMapper { @Select("SELECT * FROM t_department")
List<Department> getAllDepartments(); @Select("SELECT * FROM t_department WHERE id = #{dp_id}")
Department getDepartmentById(@Param("dp_id") Integer id); @Delete("DELETE FROM t_department WHERE id = #{dp_id}")
int deleteDepartmentById(@Param("dp_id")Integer id); @Insert("INSERT INTO t_department(department_name) VALUES(#{name})")
int addDepartment(@Param("name") String department_name); @Update("UPDATE t_department SET department_name = #{department_name} WHERE id = #{id}")
int updateDepartmentById(Department department); }

测试使用的部门控制器,通过地址参数进行SQL测试

package cn.dai.controller;

import cn.dai.mapper.DepartmentMapper;
import cn.dai.pojo.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController; import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List; /**
* @author ArkD42
* @file SpringBoot with Mybatis
* @create 2020 - 05 - 31 - 23:02
*/ @RestController
public class DepartmentController { @Autowired
DepartmentMapper departmentMapper; @GetMapping("/department/get_by_id/{id}")
public Department getDepartmentById(@PathVariable("id") Integer id){
return departmentMapper.getDepartmentById(id);
} @GetMapping("/department/listAll")
public List<Department> getAllDepartments(){
return departmentMapper.getAllDepartments();
} @GetMapping("/department/del_by_id/{id}")
public String deleteDepartmentById(@PathVariable("id")Integer id){
return "删除结果:" + departmentMapper.deleteDepartmentById(id);
} @GetMapping("/department/update_by_id/{dept}")
public String updateDepartmentById(@PathVariable("dept")Department department){
return "更新结果:" + departmentMapper.updateDepartmentById(department);
} @GetMapping("/department/add/{dept_name}")
public String addDepartment(@PathVariable("dept_name")String name) throws UnsupportedEncodingException {
String decode = URLDecoder.decode(name, "utf-8");
return "添加结果:" + departmentMapper.addDepartment(decode);
} }

不过这里要注意的一点是这个自动装配会爆红警告,说无法装配,因为没有注册这个部门映射接口Bean类型

直接无视测试运行

测试结果

查询所有部门

按ID查询部门

然后是这个通过名字查询出现了BUG

因为地址栏解析会变成URL字符,这里要变换成UTF8注入才行

然后更改为URL解码即可

    @GetMapping("/department/add/{dept_name}")
public String addDepartment(@PathVariable("dept_name")String name) throws UnsupportedEncodingException {
String decode = URLDecoder.decode(name, "utf-8");
return "添加结果:" + departmentMapper.addDepartment(decode);
}

在原生Mybatis的时候一切设置交给Mybatis核心配置文件设置xml标签完成

如果整合的是Spring容器,则通过SQL会话工厂Bean注入配置完成

现在在SpringBoot中,我们通过自定义配置类来实现这个功能

package cn.dai.config;

import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean; /**
* @author ArkD42
* @file SpringBoot with Mybatis
* @create 2020 - 06 - 01 - 11:23
*/
//自定义Mybatis配置规则
@org.springframework.context.annotation.Configuration
public class MybatisConfig { @Bean
public ConfigurationCustomizer configurationCustomizer(){ return new ConfigurationCustomizer(){ @Override
public void customize(Configuration configuration) { // 开启驼峰命名,如果这里的ORM和表字段一样,不要开启
//configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}

另外,如果映射接口数量众多,不可能每一个接口都要这样打注解Mapper

所以我们需要这样一个注解@MapperScan打在启动Main类

在Main入口类中

注意和MapperScans区分开来,这个是没有S的

2、【使用配置文件完成映射配置】

Mybatis的配置文件包括核心配置文件和映射配置

我们先来编写映射接口

package cn.dai.mapper;

import cn.dai.pojo.Employee;

import java.util.List;

/**
* @author ArkD42
* @file SpringBoot with Mybatis
* @create 2020 - 06 - 01 - 11:35
*/ public interface EmployeeMapper { List<Employee> getAllEmployees(); Employee getEmployeeById(); int addEmployee(Employee employee); int deleteEmployeeById(Integer id); int updateEmployeeById(Employee employee);
}

这里不用注解则采用原生Mybatis映射器配置【EmployeeMapper.xml】

<?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="cn.dai.mapper.EmployeeMapper">
<!--
List<Employee> getAllEmployees(); Employee getEmployeeById(); int addEmployee(Employee employee); int deleteEmployeeById(Integer id); int updateEmployeeById(Employee employee);
--> <select id="getAllEmployees" resultType="cn.dai.pojo.Employee">
SELECT * FROM t_employee
</select> <select id="getEmployeeById" resultType="cn.dai.pojo.Employee">
SELECT * FROM t_employee WHERE id = #{emp_id}
</select> <insert id="addEmployee" parameterType="cn.dai.pojo.Employee">
INSERT INTO t_employee(last_name,email,gender,department_id)
VALUES(#{last_name},#{email},#{gender},#{department_id})
</insert> <delete id="deleteEmployeeById" parameterType="int">
DELETE FROM t_employee WHERE id = #{id}
</delete> <update id="updateEmployeeById" parameterType="int">
UPDATE
t_employee
SET
last_name = #{last_name},
email = #{email},
gender = #{gender},
department_id = #{department_id}
WHERE
id = #{id}
</update> </mapper>

要让SpringBoot加载原生Mybatis的XML配置,就必须在配置信息中加入这些东西

mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml

这里还忘了核心XML配置,补上

【注意这个核心配置文件,不需要写映射器注册,这个工作在SpringBoot配置信息里设置】

【否则重复注册会导致SpringBoot启动异常,说找不到这个Bean,然后结尾是导入注册异常】

<?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> </configuration>

配置文件位置

在SpringBoot中配置Mybatis配置文件的信息

mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml

然后编写员工表测试控制器类

package cn.dai.controller;

import cn.dai.mapper.EmployeeMapper;
import cn.dai.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController; import java.util.List; /**
* @author ArkD42
* @file SpringBoot with Mybatis
* @create 2020 - 06 - 01 - 13:28
*/ @RestController
public class EmployeeController { @Autowired
EmployeeMapper employeeMapper; @GetMapping("/employee/listAll")
public List<Employee> getAllEmployees(){
return employeeMapper.getAllEmployees();
} @GetMapping("/employee/get_by_id/{emp_id}")
public Employee getEmployeeById(@PathVariable("emp_id") Integer id){
return employeeMapper.getEmployeeById();
} @PostMapping("/employee/add")
public String addEmployee(Employee employee){
return "添加结果:" + employeeMapper.addEmployee(employee);
} @GetMapping("/employee/del_by_id/{emp_id}")
public String deleteEmployeeById(@PathVariable("emp_id") Integer id){
return "删除结果:" + employeeMapper.deleteEmployeeById(id);
} @PostMapping("/employee/upd_by_id/")
public String updateEmployeeById(Employee employee){
return "修改结果:" + employeeMapper.updateEmployeeById(employee);
} }

测试结果

关于Mybatis的一些Dao设置也可以在核心配置中设置

总结:

一定要注意跟映射接口相关的映射器配置,不要重复性注册映射器

遇上找不到的异常错误,一般都出现在这个问题上面,仔细留意

【另外跟重复设置有关的还有日志输出,等等,都是因为重复配置导致的问题】

【SpringBoot】15 数据访问P3 整合Mybatis的更多相关文章

  1. java框架之SpringBoot(9)-数据访问及整合MyBatis

    简介 对于数据访问层,无论是 SQL 还是 NOSQL,SpringBoot 默认采用整合 SpringData 的方式进行统一处理,添加了大量的自动配置,引入了各种 Template.Reposit ...

  2. SpringBoot数据访问之整合mybatis注解版

    SpringBoot数据访问之整合mybatis注解版 mybatis注解版: 贴心链接:Github 在网页下方,找到快速开始文档 上述链接方便读者查找. 通过快速开始文档,搭建环境: 创建数据库: ...

  3. SpringBoot数据访问之整合Mybatis配置文件

    环境搭建以及前置知识回顾 SpringBoot中有两种start的形式: 官方:spring-boot-starter-* 第三方:*-spring-boot-starter Mybatis属于第三方 ...

  4. Spring Boot数据访问之整合Mybatis

    在Mybatis整合Spring - 池塘里洗澡的鸭子 - 博客园 (cnblogs.com)中谈到了Spring和Mybatis整合需要整合的点在哪些方面,需要将Mybatis中数据库连接池等相关对 ...

  5. 六、SpringBoot与数据访问

    六.SpringBoot与数据访问 1.JDBC spring: datasource: username: root password: 123456 url: jdbc:mysql://192.1 ...

  6. SpringBoot之数据访问和事务-专题三

    SpringBoot之数据访问和事务-专题三 四.数据访问 4.1.springboot整合使用JdbcTemplate 4.1.1 pom文件引入 <parent> <groupI ...

  7. springboot使用之二:整合mybatis(xml方式)并添加PageHelper插件

    整合mybatis实在前面项目的基础上进行的,前面项目具体整合请参照springboot使用之一. 一.整合mybatis 整合mybatis的时候可以从mybatis官网下载mybatis官网整合的 ...

  8. SpringBoot的数据访问

    一.JDBC方式 引入starter. <dependency> <groupId>org.springframework.boot</groupId> <a ...

  9. SpringBoot(九) -- SpringBoot与数据访问

    一.简介 对于数据访问层,无论是SQL还是NOSQL,Spring Boot默认采用整合Spring Data的方式进行统一处理,添加大量自动配置,屏蔽了很多设置.引入各种xxxTemplate,xx ...

  10. SpringBoot 之数据访问

    1. Spring Boot 与 JDBC 默认使用 org.apache.tomcat.jdbc.pool.DataSource 数据源; // application.yml spring: da ...

随机推荐

  1. 纯css+html+js模仿elementui组件

    文件下载链接地址https://files.cnblogs.com/files/ht955/UIcomponents.zip?t=1717405975&download=true

  2. 引用(包含) import wxss样式

    引用(包含) 把模板定义到外部,然后多个页面间可以共用使用定义的模板WXML结构显示. https://developers.weixin.qq.com/miniprogram/dev/referen ...

  3. Python BeautifulSoup定位取值

    -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* ...

  4. flutter 创建第一个项目(二)

    新建flutter project 项目 这样就创建出了第一个项目

  5. FEL - Fast Expression Language

    开源好用的表达式计算语言FEL,可惜了官网文档不在国内,我来copy个过来. Fel是轻量级的高效的表达式计算引擎 Fel在源自于企业项目,设计目标是为了满足不断变化的功能需求和性能需求. Fel是开 ...

  6. [flask]统一API响应格式

    前言 在设计API返回内容时,通常需要与前端约定好API返回响应体内容的格式.这样方便前端进行数据反序列化时相应的解析处理,也方便其它服务调用.不同公司有不同的响应内容规范要求,这里以常见的JSON响 ...

  7. SVG <pattern> 标签的用法和应用场景

    通过使用 <pattern> 标签,可以在 SVG 图像内部定义可重复使用的任意图案.这些图案可以通过 fill 属性或 stroke 属性进行引用. 使用场景 例如我们要在 <sv ...

  8. 一文学完所有的Hive Sql(两万字最全详解)

    Hive Sql 大全 本文基本涵盖了Hive日常使用的所有SQL,因为SQL太多,所以将SQL进行了如下分类: 一.DDL语句(数据定义语句): 对数据库的操作:包含创建.修改数据库 对数据表的操作 ...

  9. 2019银川区域赛BDFGHIKN题解

    B.So Easy 题目大意:给你一个正方形矩阵,初始都是0,题目对这个矩阵做了许多次操作,每次操作把行+1或列+1.其中有一个元素被隐藏了,你需要找出这个被隐藏的元素并判断它在操作之后应该是多少. ...

  10. python json反序列化为对象

    在Python中,将JSON数据反序列化为对象通常意味着将JSON格式的字符串转换为一个Python的数据结构(如列表.字典)或者一个自定义的类实例.虽然Python的标准库json模块不提供直接将J ...