目录

1、配置pom.xml

2、配置application.yml

3、配置DruidConfig关联yml的配置文件spring.datasource

4、创建数据库及数据库表结构

5、创建对应的实体类

1)Department

2)Employee

6、创建对应的Mapper

1)创建DepartmentMapper

7、创建DeptController

8、浏览器访问

1)新增测试:

返回结果

2)查询测试:

返回结果

9、解决驼峰命名问题

1)使用配置类的方式

2)使用配置文件的方式

10、省写@Mapper 注解,统一配置在启动入口

11、配置文件的方式整合Mybatis

1)创建EmployeeMapper类

2)创建mybatis/mapper/EmployeeMapper.xml

3)创建mybatis/mybatis-config.xml

4) 在application.yml文件中配置mybatis文件的位置

5)创建EmpController类

6)测试配置版springboot整合mybatis

1、配置pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.6.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.mi</groupId><artifactId>spring-boot-mybatis</artifactId><version>0.0.1-SNAPSHOT</version><name>spring-boot-mybatis</name><description>spring-boot-mybatis project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.0.1</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><!--引入自定义数据源--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.18</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

2、配置application.yml

spring:datasource:username: rootpassword: rooturl: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTCdriver-class-name: com.mysql.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSourceinitialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true
#   配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙filters: stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500schema:- classpath:sql/department.sql- classpath:sql/employee.sql

3、配置DruidConfig关联yml的配置文件spring.datasource

package com.mi.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;/*** Created by chengwen on 2019/7/3.*/
@Configuration
public class DruidConfig {@Bean@ConfigurationProperties(prefix = "spring.datasource")public DataSource druid(){return new DruidDataSource();}//配置Druid的监控//1、配置一个管理后台的servlet@Beanpublic ServletRegistrationBean statViewServlet(){ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");Map<String,String> initParms = new HashMap<>();initParms.put("loginUsername","admin");initParms.put("loginPassword","123456");initParms.put("allow",""); //默认是允许所有访问initParms.put("deny","192.168.15.21"); //不允许访问bean.setInitParameters(initParms);return bean;}//2、配置一个监控的filter@Beanpublic FilterRegistrationBean webStatFilter(){FilterRegistrationBean bean = new FilterRegistrationBean();bean.setFilter(new WebStatFilter());Map<String,String> initParms = new HashMap<>();initParms.put("exclusions","*.js,*.css,/druid/*");bean.setInitParameters(initParms);bean.setUrlPatterns(Arrays.asList("/*"));return bean;}
}

4、创建数据库及数据库表结构

SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for department
-- ----------------------------
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (`id` int(11) NOT NULL AUTO_INCREMENT,`departmentName` varchar(255) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;SET FOREIGN_KEY_CHECKS=0;-- ----------------------------
-- Table structure for employee
-- ----------------------------
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (`id` int(11) NOT NULL AUTO_INCREMENT,`lastName` varchar(255) DEFAULT NULL,`email` varchar(255) DEFAULT NULL,`gender` int(2) DEFAULT NULL,`d_id` int(11) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

5、创建对应的实体类
1)Department

package com.mi.bean;
/*** Created by chengwen on 2019/7/3.*/
public class Department {private  Integer id;private String departmentName;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getDepartmentName() {return departmentName;}public void setDepartmentName(String departmentName) {this.departmentName = departmentName;}
}

2)Employee

package com.mi.bean;/*** Created by chengwen on 2019/7/3.*/
public class Employee {private Integer id;private String lastName;private Integer gender;private String email;private Integer dId;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getLastName() {return lastName;}public void setLastName(String lastName) {this.lastName = lastName;}public Integer getGender() {return gender;}public void setGender(Integer gender) {this.gender = gender;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public Integer getdId() {return dId;}public void setdId(Integer dId) {this.dId = dId;}
}

6、创建对应的Mapper
1)创建DepartmentMapper

package com.mi.mapper;
import com.mi.bean.Department;
import org.apache.ibatis.annotations.*;/*** Created by chengwen on 2019/7/3.*/
//指定这是一个操作数据库的Mapper
@Mapper
public interface DepartmentMapper {@Select("select * from department where id=#{id}")public Department getDeptById(Integer id);@Delete("delete from department where id=#{id}")public int deleteDeptById(Integer id);//@Options注解用于获取自增主键返回给前端@Options(useGeneratedKeys = true,keyProperty = "id")@Options(useGeneratedKeys = true,keyProperty = "id")@Insert("insert into department(departmentName) values (#{departmentName})")public int insertDept(Department department);@Update("update department set departmentName=#{departmentName} where id=#{id}")public int updateDept(Department department);}

7、创建DeptController

package com.mi.controller;import com.mi.bean.Department;
import com.mi.mapper.DepartmentMapper;
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;/*** Created by chengwen on 2019/7/3.*/
@RestController
public class DeptController {@AutowiredDepartmentMapper departmentMapper;@GetMapping("dept/{id}")public Department getDepartment(@PathVariable("id") Integer id){return departmentMapper.getDeptById(id);}@GetMapping("dept")public Department insertDept(Department department){departmentMapper.insertDept(department);return department;}
}

8、浏览器访问
1)新增测试:

http://localhost:8080/dept?departmentName=CC

返回结果

{"id":3,"departmentName":"CC"}

2)查询测试:

http://localhost:8080/dept/1

返回结果

{"id":1,"departmentName":"AA"}

9、解决驼峰命名问题

可以使实体类的驼峰命名与数据库的下划线映射成功。

1)使用配置类的方式

package com.mi.config;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;/*** Created by chengwen on 2019/7/3.*/
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {@Beanpublic ConfigurationCustomizer configurationCustomizer(){return new ConfigurationCustomizer() {@Overridepublic void customize(Configuration configuration){configuration.setMapUnderscoreToCamelCase(true);}};}
}

2)使用配置文件的方式

在application.yml文件中添加配置

# 解决驼峰命名问题
mybatis:configuration:map-underscore-to-camel-case: true

10、省写@Mapper 注解,统一配置在启动入口

使用@MapperScan(value = "com.mi.mapper")扫描所有Mapper文件

package com.mi;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@MapperScan(value = "com.mi.mapper")
@SpringBootApplication
public class SpringBootMybatisApplication {public static void main(String[] args) {SpringApplication.run(SpringBootMybatisApplication.class, args);}}

11、配置文件的方式整合Mybatis
1)创建EmployeeMapper类

package com.mi.mapper;
import com.mi.bean.Employee;
import org.apache.ibatis.annotations.Mapper;/*** Created by chengwen on 2019/7/3.*/
//@Mapper或者mapperScan将接口扫描到容器中
public interface EmployeeMapper {public Employee getEmpById(Integer id);public void insertEmp(Employee employee);
}

2)创建mybatis/mapper/EmployeeMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mi.mapper.EmployeeMapper"><select id="getEmpById" resultType="com.mi.bean.Employee">SELECT * FROM employee WHERE id=#{id}</select><insert id="insertEmp">INSERT INTO employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{did})</insert>
</mapper>

3)创建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><settings><setting name="mapUnderscoreToCamelCase" value="true"/></settings>
</configuration>

4) 在application.yml文件中配置mybatis文件的位置

spring:datasource:username: rootpassword: rooturl: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTCdriver-class-name: com.mysql.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSourceinitialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true
#   配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙filters: stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500#schema:#  - classpath:sql/department.sql#  - classpath:sql/employee.sql
# 解决驼峰命名问题
mybatis:#configuration:#  map-underscore-to-camel-case: true#配置文件的方式整合mybatisconfig-location: classpath:/mybatis/mybatis-config.xmlmapper-locations: classpath:/mybatis/mapper/*.xml

5)创建EmpController类

package com.mi.controller;
import com.mi.bean.Employee;
import com.mi.mapper.EmployeeMapper;
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;/*** Created by chengwen on 2019/7/3.*/
@RestController
public class EmpController {@AutowiredEmployeeMapper employeeMapper;@GetMapping("emp/{id}")public Employee getEmp(@PathVariable("id") Integer id){return employeeMapper.getEmpById(id);}}

6)测试配置版springboot整合mybatis

http://localhost:8080/emp/1

测试结果

{"id":1,"lastName":"zhangsan","gender":1,"email":"zhangsan@163.com","dId":1}

3、SpringBoot整合MyBatis注解版及配置文件版相关推荐

  1. 第 5 课 SpringBoot集成Mybatis(2)-配置文件版

    第五课 SpringBoot集成Mybatis(2)-配置文件版 文章目录 第五课 SpringBoot集成Mybatis(2)-配置文件版 1. 引入依赖:pom.xml 2. 配置applicat ...

  2. SpringBoot整合Mybatis超详细流程

    SpringBoot整合Mybatis超详细流程 文章目录 SpringBoot整合Mybatis超详细流程 前言 详细流程 0.引入Mybatis 1.创建数据 2.创建程序目录 3.理解后台访问流 ...

  3. (一)SpringBoot 整合 MyBatis

    一.工具 IDE:idea.DB:mysql 二.创建SpringBoot工程 在Idea中使用SpringInitializr模板创建SpringBoot工程,依赖选择如下: 这里也可以不选JDBC ...

  4. SpringBoot整合mybatis、shiro、redis实现基于数据库的细粒度动态权限管理系统实例(转)...

    SpringBoot整合mybatis.shiro.redis实现基于数据库的细粒度动态权限管理系统实例 shiro 目录(?)[+] 前言 表结构 maven配置 配置Druid 配置mybatis ...

  5. SpringBoot整合Mybatis(高级)

    SpringBoot整合Mybatis(高级) 文章目录 SpringBoot整合Mybatis(高级) 前言 基础环境配置 增删改查 ResultMap 复杂查询 多对一 一对多 动态SQL if ...

  6. SpringBoot整合Mybatis,并实现事务控制

    SpringBoot整合Mybatis,并实现事务控制 1. 在pom文件里添加相关maven文件 <parent><groupId>org.springframework.b ...

  7. Spring Boot整合MyBatis框架(XML文件版)

    1.创建数据库.数据库表并插入数据 创建数据库springboot: CREATE DATABASE springboot; 创建数据库表user: CREATE TABLE `user` (`id` ...

  8. springboot整合mybatis

    3.springboot整合mybatis 首先新建一个项目,勾选上我们需要的 1.springboot配置数据库连接池druid druid学习地址 https://github.com/aliba ...

  9. SpringBoot整合Mybatis演示

    SpringBoot整合Mybatis演示 1.环境准备 JDK 1.8 MySQL 5.7 Maven 3.6.3 Idea 2020.1.1 数据库模拟数据准备: CREATE DATABASE ...

最新文章

  1. 高校毕业生:今年“太惨了”,网友:更惨的可能还在后头!
  2. eclipse提示edit source lookup path的问题
  3. F(n)完全覆盖中的计数问题
  4. 自下而上归并排序 数组实现
  5. javascript实现汉诺塔动画效果
  6. java查看weblogic服务器_java判断服务器是那种,例如区分tomcat和weblogic | 学步园
  7. qt中QHBoxLayout或QVBoxLayout布局内控件的动态生成与显示
  8. linux服务启动redis自动启动不了,linux开机启动redis、nginx等服务
  9. Oracle-随笔笔记
  10. 函数式编程基础---高阶函数和偏函数
  11. 传统IT架构转型,从云原生平台到微服务应用构建
  12. 【新东方的全套价值上亿英语资料】好不容易搞到的~
  13. matlab瓶盖盖严检查,口服液瓶盖密封性的质量检测方法你知道吗?
  14. Element UI 进度条文字样式修改
  15. 留学生论文essay写作字数不够怎么办?
  16. DB9针型:RS485输出信号及接线端子引脚分配
  17. 条码打印软件中多列不干胶标签纸的设置方法
  18. 新姿势 - 海贼王之伟大航路
  19. 达观数据ISIG中国产业智能大会包揽四项大奖、五大演讲
  20. MFC中使用CPropertySheet实现Tab Control

热门文章

  1. Ubuntu ORTP 编译及安装
  2. python3字符编码str_聊聊Python 3 的字符串:str 和 bytes 的区别
  3. mysql 触发器_进阶msql触发器-指南
  4. 你需要来自trustedinstaller的权限才能删除_前后端分离后的权限控制设计方案
  5. cpu烤机工具_MySQL常用工具选择和建议
  6. php cannot find libz,brew安装php70出现configure: error: Cannot find libz 错误解决方法
  7. python编码解码的过程_使用Python过程中的编码和解码
  8. 计算机职称excel2007,职称计算机Excel2007中文电子表格考试大纲
  9. ansys怎么批量输入点坐标_当SpaceClaim 遇上ANSYS (二)
  10. 逆序输出螺旋字符矩阵(三种方法)