文章目录
1.整合MyBatis
1.需求分析
2.数据库表设计
CREATEDATABASE`springboot_mybatis`;use`springboot_mybatis`;CREATETABLE`monster`(`id`INTNOTNULLAUTO_INCREMENT,`age`INTNOTNULL,`birthday`DATEDEFAULTNULL,`email`VARCHAR(255)DEFAULTNULL,`gender`char(1)DEFAULTNULL,`name`VARCHAR(255)DEFAULTNULL,`salary`DOUBLENOTNULL,PRIMARYKEY(`id`));SELECT*FROM`monster`;insertinto monster values(null,20,'2000-11-11','[email protected]','男','牛魔王',5000.88);insertinto monster values(null,10,'2011-11-11','[email protected]','女','白骨精',2000.00);
3.数据库环境配置
1.新建maven项目
2.pom.xml 引入依赖
<!--导入springboot父工程--><parent><artifactId>spring-boot-starter-parent</artifactId><groupId>org.springframework.boot</groupId><version>2.5.3</version></parent><!--引入相关依赖--><dependencies><!--常规依赖--><!--web场景启动器--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></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-configuration-processor</artifactId><optional>true</optional></dependency><!--数据库配置--><!--引入data-jdbc数据源--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jdbc</artifactId></dependency><!--mysql依赖使用版本仲裁--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><!-- 引入 druid 依赖 --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.17</version></dependency><!--MyBatis场景启动器--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.2</version></dependency></dependencies>
3.application.yml 配置数据源
- 数据库名
- 用户名
- 密码
- 驱动是mysql8的(因为上面使用了版本仲裁)
server:port:8080spring:datasource:#配置数据源url: jdbc:mysql://localhost:3306/springboot_mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
4.Application.java 编写启动类
packagecom.sun.springboot.mybatis;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;/**
* @author 孙显圣
* @version 1.0
*/@SpringBootApplicationpublicclassApplication{publicstaticvoidmain(String[] args){SpringApplication.run(Application.class, args);}}
5.测试
packagecom.sun.springboot.mybatis;importorg.junit.jupiter.api.Test;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.jdbc.core.JdbcTemplate;importjavax.annotation.Resource;/**
* @author 孙显圣
* @version 1.0
*/@SpringBootTestpublicclassApplicationTest{//依赖注入@ResourceprivateJdbcTemplate jdbcTemplate;@Testpublicvoidt1(){//查看目前数据源System.out.println(jdbcTemplate.getDataSource().getClass());}}
6.配置类切换druid数据源
packagecom.sun.springboot.mybatis.config;importcom.alibaba.druid.pool.DruidDataSource;importcom.alibaba.druid.support.http.StatViewServlet;importcom.alibaba.druid.support.http.WebStatFilter;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.boot.web.servlet.FilterRegistrationBean;importorg.springframework.boot.web.servlet.ServletRegistrationBean;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importjavax.sql.DataSource;importjava.sql.SQLException;importjava.util.Arrays;/**
* @author 孙显圣
* @version 1.0
*/@ConfigurationpublicclassDruidDataSourceConfig{//注入一个德鲁伊数据源@ConfigurationProperties("spring.datasource")//读取yaml配置文件的参数,获取数据源配置@BeanpublicDataSourcedataSource()throwsSQLException{DruidDataSource druidDataSource =newDruidDataSource();
druidDataSource.setFilters("stat, wall");//开启sql监控return druidDataSource;}//配置德鲁伊监控sql功能@BeanpublicServletRegistrationBeanstatViewServlet(){StatViewServlet statViewServlet =newStatViewServlet();ServletRegistrationBean<StatViewServlet> registrationBean =newServletRegistrationBean<>(statViewServlet,"/druid/*");//配置登录监控页面用户名和密码
registrationBean.addInitParameter("loginUsername","root");
registrationBean.addInitParameter("loginPassword","root");return registrationBean;}//配置webStatFilter@BeanpublicFilterRegistrationBeanwebStatFilter(){WebStatFilter webStatFilter =newWebStatFilter();FilterRegistrationBean<WebStatFilter> filterRegistrationBean =newFilterRegistrationBean<>(webStatFilter);//默认对所有 URL 请求监控
filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));//排除 URL
filterRegistrationBean.addInitParameter
("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");return filterRegistrationBean;}}
7.测试数据源是否成功切换
packagecom.sun.springboot.mybatis;importorg.junit.jupiter.api.Test;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.jdbc.core.JdbcTemplate;importjavax.annotation.Resource;/**
* @author 孙显圣
* @version 1.0
*/@SpringBootTestpublicclassApplicationTest{//依赖注入@ResourceprivateJdbcTemplate jdbcTemplate;@Testpublicvoidt1(){//查看目前数据源System.out.println(jdbcTemplate.getDataSource().getClass());}}
4.Mybatis基础配置
1.编写映射表的bean
packagecom.sun.springboot.mybatis.bean;importcom.fasterxml.jackson.annotation.JsonFormat;importlombok.Data;importjava.util.Date;/**
* @author 孙显圣
* @version 1.0
*/@DatapublicclassMonster{privateInteger id;privateInteger age;@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")privateDate birthday;privateString email;privateString name;privateString gender;privateDouble salary;}
2.MonsterMapper.java 编写mapper接口
- 使用注解注入容器
packagecom.sun.springboot.mybatis.mapper;importcom.sun.springboot.mybatis.bean.Monster;importorg.apache.ibatis.annotations.Mapper;/**
* @author 孙显圣
* @version 1.0
*/@Mapper//将接口注入容器publicinterfaceMonsterMapper{publicMonstergetMonsterById(Integer id);}
3.MonsterMapper.xml 编写mapper.xml实现mapper接口
- 使用namespace指定要实现的接口
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""https://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--指定要实现的接口--><mappernamespace="com.sun.springboot.mybatis.mapper.MonsterMapper"><selectid="getMonsterById"resultType="com.sun.springboot.mybatis.bean.Monster"parameterType="Integer">
select * from monster where id = #{id}
</select></mapper>
4.application.yml 扫描mapper.xml配置文件的位置
- 扫描类路径下mapper文件夹下的所有文件
mybatis:#指定要扫描的mapper.xmlmapper-locations: classpath:mapper/*.xml
5.测试
packagecom.sun.springboot.mybatis;importcom.sun.springboot.mybatis.bean.Monster;importcom.sun.springboot.mybatis.mapper.MonsterMapper;importorg.junit.jupiter.api.Test;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.jdbc.core.JdbcTemplate;importjavax.annotation.Resource;/**
* @author 孙显圣
* @version 1.0
*/@SpringBootTestpublicclassApplicationTest{//依赖注入@ResourceprivateJdbcTemplate jdbcTemplate;//注意这里注入的是MonsterMapper的代理对象@ResourceprivateMonsterMapper monsterMapper;@Testpublicvoidt1(){//查看目前数据源System.out.println(jdbcTemplate.getDataSource().getClass());}@Testpublicvoidt2(){//测试mybatisMonster monsterById = monsterMapper.getMonsterById(1);System.out.println(monsterById);}}
5.MyBatis高级配置
1.方式一:在application.yml中配置mybatis.config-location指定mybatis-config.xml配置文件的位置
2.方式二:直接在application.yml中配置
mybatis:#指定要扫描的mapper.xmlmapper-locations: classpath:mapper/*.xml#配置类型别名包,这样只要在这个包下的类型都可以简写type-aliases-package: com/sun/springboot/mybatis/bean
#输出日志configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
6.继续编写Service层和Controller层
1.MonsterService.java
packagecom.sun.springboot.mybatis.service;importcom.sun.springboot.mybatis.bean.Monster;/**
* @author 孙显圣
* @version 1.0
*/publicinterfaceMonsterService{publicMonstergetMonsterById(Integer id);}
2.MonsterServiceImpl.java
packagecom.sun.springboot.mybatis.service.Impl;importcom.sun.springboot.mybatis.bean.Monster;importcom.sun.springboot.mybatis.mapper.MonsterMapper;importcom.sun.springboot.mybatis.service.MonsterService;importorg.springframework.stereotype.Service;importjavax.annotation.Resource;/**
* @author 孙显圣
* @version 1.0
*/@ServicepublicclassMonsterServiceImplimplementsMonsterService{@ResourceprivateMonsterMapper monsterMapper;//返回代理对象@OverridepublicMonstergetMonsterById(Integer id){return monsterMapper.getMonsterById(id);}}
3.测试
packagecom.sun.springboot.mybatis;importcom.sun.springboot.mybatis.bean.Monster;importcom.sun.springboot.mybatis.mapper.MonsterMapper;importcom.sun.springboot.mybatis.service.MonsterService;importorg.junit.jupiter.api.Test;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.jdbc.core.JdbcTemplate;importjavax.annotation.Resource;/**
* @author 孙显圣
* @version 1.0
*/@SpringBootTestpublicclassApplicationTest{//依赖注入@ResourceprivateMonsterService monsterService;@TestpublicvoidgetMonsterById(){Monster monsterById = monsterService.getMonsterById(1);System.out.println(monsterById);}}
4.MonsterController.java
packagecom.sun.springboot.mybatis.Controller;importcom.sun.springboot.mybatis.bean.Monster;importcom.sun.springboot.mybatis.service.MonsterService;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.PathVariable;importorg.springframework.web.bind.annotation.ResponseBody;importjavax.annotation.Resource;/**
* @author 孙显圣
* @version 1.0
*/@ControllerpublicclassMonsterController{@ResourceprivateMonsterService monsterService;@GetMapping("/getMonster/{id}")//路径参数的请求@ResponseBody//响应一个jsonpublicMonstergetMonsterById(@PathVariable("id")Integer id){Monster monsterById = monsterService.getMonsterById(id);return monsterById;}}
5.测试
6.解决时间问题
7.完整文件目录
2.整合MyBatis-Plus
1.MyBatis-Plus基本介绍
2.数据库表设计
CREATEDATABASE`springboot_mybatisplus`;USE`springboot_mybatisplus`;CREATETABLE`monster`(`id`INTNOTNULLAUTO_INCREMENT,`age`INTNOTNULL,`birthday`DATEDEFAULTNULL,`email`VARCHAR(255)DEFAULTNULL,`gender`CHAR(1)DEFAULTNULL,`name`VARCHAR(255)DEFAULTNULL,`salary`DOUBLENOTNULL,PRIMARYKEY(`id`));SELECT*FROM`monster`;INSERTINTO monster VALUES(NULL,20,'2000-11-11','[email protected]','男',' 蝎 子 精 ',15000.88);INSERTINTO monster VALUES(NULL,10,'2011-11-11','[email protected]','女',' 玉 兔 精 ',18000.88);
3.数据库环境配置
1.创建maven项目
2.pom.xml 导入依赖
<!--导入springboot父工程--><parent><artifactId>spring-boot-starter-parent</artifactId><groupId>org.springframework.boot</groupId><version>2.5.3</version></parent><!--引入相关依赖--><dependencies><!--常规依赖--><!--web场景启动器--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></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-configuration-processor</artifactId><optional>true</optional></dependency><!--数据库配置--><!--mysql依赖使用版本仲裁--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><!-- 引入 druid 依赖 --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.17</version></dependency><!--引入MyBatis-Plus场景启动器,会自动引入jdbc和MyBatis--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.3</version></dependency></dependencies>
3.application.yml 配置数据源
- 数据库名称
- 用户名
- 密码
server:port:8080spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot_mybatisplus?useSSL=false&useUnicode=true&characterEncoding=UTF-8username: root
password: root
4.DruidDataSourceConfig.java 配置类切换druid数据源
packagecom.sun.springboot.mybatisplus.config;importcom.alibaba.druid.pool.DruidDataSource;importcom.alibaba.druid.support.http.StatViewServlet;importcom.alibaba.druid.support.http.WebStatFilter;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.boot.web.servlet.FilterRegistrationBean;importorg.springframework.boot.web.servlet.ServletRegistrationBean;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importjavax.sql.DataSource;importjava.sql.SQLException;importjava.util.Arrays;/**
* @author 孙显圣
* @version 1.0
*/@ConfigurationpublicclassDruidDataSourceConfig{//注入一个德鲁伊数据源@ConfigurationProperties("spring.datasource")//读取yaml配置文件的参数,获取数据源配置@BeanpublicDataSourcedataSource()throwsSQLException{DruidDataSource druidDataSource =newDruidDataSource();
druidDataSource.setFilters("stat, wall");//开启sql监控return druidDataSource;}//配置德鲁伊监控sql功能@BeanpublicServletRegistrationBeanstatViewServlet(){StatViewServlet statViewServlet =newStatViewServlet();ServletRegistrationBean<StatViewServlet> registrationBean =newServletRegistrationBean<>(statViewServlet,"/druid/*");//配置登录监控页面用户名和密码
registrationBean.addInitParameter("loginUsername","root");
registrationBean.addInitParameter("loginPassword","root");return registrationBean;}//配置webStatFilter@BeanpublicFilterRegistrationBeanwebStatFilter(){WebStatFilter webStatFilter =newWebStatFilter();FilterRegistrationBean<WebStatFilter> filterRegistrationBean =newFilterRegistrationBean<>(webStatFilter);//默认对所有 URL 请求监控
filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));//排除 URL
filterRegistrationBean.addInitParameter
("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");return filterRegistrationBean;}}
5.编写启动类Application.java,测试运行
packagecom.sun.springboot.mybatisplus;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;/**
* @author 孙显圣
* @version 1.0
*/@SpringBootApplicationpublicclassApplication{publicstaticvoidmain(String[] args){SpringApplication.run(Application.class, args);}}
4.MyBatis-Plus基础配置
1.编写映射表的bean
packagecom.sun.springboot.mybatisplus.bean;importcom.fasterxml.jackson.annotation.JsonFormat;importlombok.Data;importjava.util.Date;/**
* @author 孙显圣
* @version 1.0
*/@DatapublicclassMonster{privateInteger id;privateInteger age;@JsonFormat(pattern ="yyyy-MM-dd HH:mm:ss", timezone ="GMT+8")privateDate birthday;privateString email;privateString name;privateString gender;privateDouble salary;}
2.MonsterMapper.java 编写Mapper接口
packagecom.sun.springboot.mybatisplus.mapper;importcom.baomidou.mybatisplus.core.mapper.BaseMapper;importcom.sun.springboot.mybatisplus.bean.Monster;importorg.apache.ibatis.annotations.Mapper;/**
* @author 孙显圣
* @version 1.0
*///直接继承BaseMapper接口@Mapper//注入容器publicinterfaceMonsterMapperextendsBaseMapper<Monster>{//如果提供的方法不够用再自定义方法}
3.测试接口方法使用
packagecom.sun.springboot.mybatisplus;importcom.sun.springboot.mybatisplus.bean.Monster;importcom.sun.springboot.mybatisplus.mapper.MonsterMapper;importorg.junit.jupiter.api.Test;importorg.springframework.boot.test.context.SpringBootTest;importjavax.annotation.Resource;/**
* @author 孙显圣
* @version 1.0
*/@SpringBootTestpublicclassMonsterMapperTest{//注入针对Mapper接口的代理对象@ResourceprivateMonsterMapper monsterMapper;@Testpublicvoidt1(){Monster monster = monsterMapper.selectById(1);System.out.println(monster);}}
5.MyBatis-Plus高级配置
application.yml 进行配置
#进行mybatis-plus配置mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
6.继续编写Service层和Controller层
1.MonsterService.java
packagecom.sun.springboot.mybatisplus.service.Impl;importcom.baomidou.mybatisplus.extension.service.impl.ServiceImpl;importcom.sun.springboot.mybatisplus.bean.Monster;importcom.sun.springboot.mybatisplus.mapper.MonsterMapper;importcom.sun.springboot.mybatisplus.service.MonsterService;importorg.springframework.stereotype.Service;/**
* 这里
* @author 孙显圣
* @version 1.0
*/@ServicepublicclassMonsterServiceImplextendsServiceImpl<MonsterMapper,Monster>implementsMonsterService{//自定义方法实现}
2.MonsterServiceImpl.java
packagecom.sun.springboot.mybatisplus.service.Impl;importcom.baomidou.mybatisplus.extension.service.impl.ServiceImpl;importcom.sun.springboot.mybatisplus.bean.Monster;importcom.sun.springboot.mybatisplus.mapper.MonsterMapper;importcom.sun.springboot.mybatisplus.service.MonsterService;importorg.springframework.stereotype.Service;/**
* 这里
* @author 孙显圣
* @version 1.0
*/@ServicepublicclassMonsterServiceImplextendsServiceImpl<MonsterMapper,Monster>implementsMonsterService{//自定义方法实现}
3.测试
packagecom.sun.springboot.mybatisplus;importcom.sun.springboot.mybatisplus.bean.Monster;importcom.sun.springboot.mybatisplus.mapper.MonsterMapper;importcom.sun.springboot.mybatisplus.service.MonsterService;importorg.junit.jupiter.api.Test;importorg.springframework.boot.test.context.SpringBootTest;importjavax.annotation.Resource;/**
* @author 孙显圣
* @version 1.0
*/@SpringBootTestpublicclassMonsterServiceTest{@ResourceprivateMonsterService monsterService;@Testpublicvoidt1(){Monster byId = monsterService.getById(2);System.out.println(byId);}}
4.细节说明
- 简单来说就是MonsterServiceImpl只需要实现MonsterService接口的方法
- 可以调用IService接口的方法,也可以调用MonsterService接口的方法
5.MonsterController.java
packagecom.sun.springboot.mybatisplus.controller;importcom.sun.springboot.mybatisplus.bean.Monster;importcom.sun.springboot.mybatisplus.service.MonsterService;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.PathVariable;importorg.springframework.web.bind.annotation.ResponseBody;importjavax.annotation.Resource;/**
* @author 孙显圣
* @version 1.0
*/@ControllerpublicclassMonsterController{@Resource//注入的是MonsterServiceImpl的bean对象,可以直接调用IService接口的方法privateMonsterService monsterService;@GetMapping("/getMonster/{id}")@ResponseBodypublicMonstergetMonsterById(@PathVariable("id")Integer id){Monster byId = monsterService.getById(id);return byId;}}
7.细节说明
1.@MapperScan 扫描包下的所有Mapper
启动类配置注解
2.@TableName bean的类名与表名不一致时使用
3.MyBatis引入了哪些依赖
8.MyBatisX快速开发
1.安装插件
2.使用方式
1.挑一个带小鸟的方法
2.直接alt + Enter
3.生成sql语句
4.查看生成的方法
5.点击左边的小鸟就可以直接跳转到指定方法或者xml
9.完整文件目录
10.MyBatis-Plus小结
本文转载自: https://blog.csdn.net/m0_64637029/article/details/136789456
版权归原作者 S-X-S 所有, 如有侵权,请联系我们删除。
版权归原作者 S-X-S 所有, 如有侵权,请联系我们删除。