目录

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. [spring-boot] 多环境配置
  2. websettings 哪里设置_云浮超级电容用石墨哪里买,可膨胀石墨_青岛天源达
  3. IOS之Swift的CoreData入门使用案例
  4. 《转载》struts旅程《2》
  5. 漫画:如何给女朋友解释什么是“锟斤拷”?
  6. Android O HIDL的使用例子 -- 蓝牙HCI 服务进程
  7. zabbix*邮件报警 *用户参数User parameters *定义key值 *Agentd主动模式与被动模式
  8. 未定义jm matlab,math – 使用Jm 1 = 2mj(m)-j(m-1)公式在MATLAB中计算bessel函数
  9. 电网调度计算机系统目前有三种,电力系统知识问答(三)
  10. 【Android 安装包优化】Android 中使用 SVG 图片 ( 批量转换 SVG 格式图片为 Vector Asset 矢量图资源 )
  11. java 变量存放在哪_Java全局变量存放在哪里?
  12. UVA1025 Thematic Contests
  13. 2013年c语言课后作业答案,C语言课后作业答案.pdf
  14. 产品黑魔法:腾讯搞流量的重要一课
  15. 线稿上色V3(比V2差别在于这个参考图的处理方式),并且更好用哦
  16. Unity使用c#开发遇上的问题(六)(3dmax围绕指定中心旋转,unity中动态调用预制体并根据模型旋转指定角度)
  17. VR全景的拍摄制作上传
  18. 认识电脑的各大组件 【主板、CPU、内存条、硬盘、显卡、显示器】
  19. 代谢组数据分析在生物医学领域的应用
  20. moment时间插件设置显示日期为周一到周日

热门文章

  1. android p 权限流程,Android native 权限控制流程
  2. java 字符串 面试_Java 字符串面试题
  3. html css js实现快递单打印_JS与HTML、CSS实现2048小游戏(六)
  4. php怎么添加会员卡,怎么在微信公众号中添加一个会员卡领取功能
  5. vscode php输出,js程序如何在vscode控制台输出
  6. python返回元组_python – numpy.where返回一个元组的目的是什么?
  7. 线索二叉树怎么画_固原超级记忆技巧课程怎么学_蒙正智升教育
  8. apply与applymap的区别
  9. php 警告提示框,关于javascript:php重定向到带有警告对话框的页面
  10. demo python_GitHub - liutao910612/DEMO_Python