五、spring boot整合mybatis-plus
spring boot整合mybatis-plus
简介
mybatis 增强工具包,简化 CRUD 操作。 文档
http://mp.baomidou.com
http://mybatis.plus
优点 | Advantages
- 无侵入:Mybatis-Plus 在 Mybatis 的基础上进行扩展,只做增强不做改变,引入 Mybatis-Plus 不会对您现有的 Mybatis 构架产生任何影响,而且 MP 支持所有 Mybatis 原生的特性
- 依赖少:仅仅依赖 Mybatis 以及 Mybatis-Spring
- 损耗小:启动即会自动注入基本CURD,性能基本无损耗,直接面向对象操作
- 预防Sql注入:内置Sql注入剥离器,有效预防Sql注入攻击
- 通用CRUD操作:内置通用Mapper、通用Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
- 多种主键策略:支持多达4种主键策略(内含分布式唯一ID生成器),可自由配置,完美解决主键问题
- 支持热加载:Mapper 对应的 XML 支持热加载,对于简单的 CRUD 操作,甚至可以无 XML 启动
- 支持ActiveRecord:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可实现基本 CRUD 操作
- 支持代码生成:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用(P.S. 比 Mybatis 官方的 Generator 更加强大!)
- 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
- 支持关键词自动转义:支持数据库关键词(order、key…)自动转义,还可自定义关键词
- 内置分页插件:基于Mybatis物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于写基本List查询
- 内置性能分析插件:可输出Sql语句以及其执行时间,建议开发测试时启用该功能,能有效解决慢查询
- 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,预防误操作
前面已经 创建了一个springboot项目,我们直接在该项目上整合mybatis-plus
准备工作
- pom.xml jar引入: <mybatis-plus.version>3.0.6</mybatis-plus.version>
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>${mybatis-plus.version}</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus</artifactId><version>${mybatis-plus.version}</version></dependency>
- 创建表
CREATE TABLE `my_info` (`id` int(10) NOT NULL AUTO_INCREMENT,`name` varchar(255) DEFAULT NULL,`age` int(3) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
项目结构
创建基本的项目结构,controller、dao、entity、service(impl)
如图:
controller :@RestController
public class MyInfoController {@ResourceMyInfoService myInfoService;@GetMapping("myInfo")public String myInfo(@RequestParam Integer id) {MyInfo myInfo = myInfoService.getById(id);return myInfo.toString();}
}dao :public interface MyInfoMapper extends BaseMapper<MyInfo> {}entity :@Data
@TableName(value = "my_info")
public class MyInfo {@TableId(type = IdType.AUTO)private Integer id;private String name;private Integer age;
}service :public interface MyInfoService {MyInfo getById(int id);
}impl :@Service("myInfoService")
public class MyInfoServiceImpl extends ServiceImpl<MyInfoMapper,MyInfo> implements MyInfoService {@Overridepublic MyInfo getById(int id) {return baseMapper.selectById(id);}
}
当前,我们也可以在xml中自定义sql( MyInfoMapper.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="com.honghh.bootfirst.dao.MyInfoMapper"><!--自定义SQL-->
</mapper>
application.yml 配置文件内容如下
spring:datasource:type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/boot_demousername: rootpassword: 123456
#mybatis
mybatis-plus:mapper-locations: classpath*:mapper/**/*.xml#实体扫描,多个package用逗号或者分号分隔typeAliasesPackage: com.honghh.bootfirst.entityglobal-config:#主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";id-type: 0#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"field-strategy: 2#驼峰下划线转换db-column-underline: true#刷新mapper 调试神器refresh-mapper: true#数据库大写下划线转换#capital-mode: true# Sequence序列接口实现类配置#key-generator: com.baomidou.mybatisplus.incrementer.OracleKeyGenerator#逻辑删除配置#logic-delete-value: -1#logic-not-delete-value: 0#自定义填充策略接口实现#meta-object-handler: com.baomidou.springboot.xxx#自定义SQL注入器sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjectorconfiguration:map-underscore-to-camel-case: truecache-enabled: falsecall-setters-on-nulls: true
启动项目
完成上面的步骤,准备工作将近完成,现在开始启动项目,但是你会发现项目启动不起来,报错如下:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myInfoController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myInfoService': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.honghh.bootfirst.dao.MyInfoMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessProperties(CommonAnnotationBeanPostProcessor.java:324) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1395) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:849) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.context.support.AbstractApplicationContext.__refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.context.support.AbstractApplicationContext.jrLockAndRefresh(AbstractApplicationContext.java:40002) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:41008) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.3.RELEASE.jar:2.1.3.RELEASE]at com.honghh.bootfirst.BootFirstApplication.main(BootFirstApplication.java:11) [classes/:na]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myInfoService': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.honghh.bootfirst.dao.MyInfoMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1395) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:204) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeanByName(AbstractAutowireCapableBeanFactory.java:452) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:526) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:496) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:636) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:180) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessProperties(CommonAnnotationBeanPostProcessor.java:321) ~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]... 19 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.honghh.bootfirst.dao.MyInfoMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1654) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1213) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1167) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]... 35 common frames omitted
上网查了一下,说一般是下面原因造成的:
- 1.applicationContext.xml配置中没有扫描包
- 2.controller层的@controller或者service层的@Service注解没写
- 3.service注入mapper失败
仔细看了下代码是mapper层没有注入,mapper注入方法有一下几种方式。
- 1.直接在mapper上写注解
@Mapper
public interface MyInfoMapper extends BaseMapper<MyInfo> {}
- 2.在启动类上添加注解
@EnableTransactionManagement
@SpringBootApplication
@MapperScan("com.honghh.*.dao")public class BootFirstApplication {public static void main(String[] args) {SpringApplication.run(BootFirstApplication.class, args);}}
mybatis-config中只是会为对应的mapper创建代理类,而想真正包装成bean,注入到spring容器中,还是需要靠AutoConfiguredMapperScannerRegistrar,它会根据扫描@Mapper注释或是@MapperScan指定的包下的接口,将其注册为bean。
- 3.也可以写一个配置类 MybatisPlusConfig
@Configuration
@MapperScan(basePackages = "com.honghh.*.dao")
public class MybatisPlusConfig {/*** mybatis-plus 分页插件*/@Beanpublic PerformanceInterceptor performanceInterceptor() {return new PerformanceInterceptor();}
}
在浏览器中输入 :http://localhost:8080/myInfo?id=1 显示如下
成功!!!此时你已经学会了整合mybatis-plus
参考文本
https://gitee.com/baomidou/mybatisplus-spring-boot
五、spring boot整合mybatis-plus相关推荐
- VUE+Spring Boot整合MyBatis实现前后端分离项目壁纸网站
目录 前言 一.项目运行 二.环境需要 三.技术栈 四.项目说明 五.后端代码 前言 每次换桌面,壁纸总是不好找,搜索图片得不到好的索引与反馈,很难找到自己喜欢的壁纸,而壁纸网站可以免去我们去寻找壁纸 ...
- Spring Boot 教程(三): Spring Boot 整合Mybatis
教程简介 本项目内容为Spring Boot教程样例.目的是通过学习本系列教程,读者可以从0到1掌握spring boot的知识,并且可以运用到项目中.如您觉得该项目对您有用,欢迎点击收藏和点赞按钮, ...
- spring boot 整合mybatis 无法输出sql的问题
使用spring boot整合mybatis,测试功能的时候,遇到到了sql问题,想要从日志上看哪里错了,但是怎么都无法输出执行的sql,我使用的是log4j2,百度了一下,很多博客都说,加上下面的日 ...
- Spring boot 整合 Mybatis 实现增删改查(MyEclipse版)
1.首先搭建好一个Spring boot 程序,编写好启动类. 启动类代码如下: @SpringBootApplication public class Start {public static vo ...
- spring boot整合mybatis+通用mapper+pagehelper分页插件
spring boot整合mybatis+通用mapper+pagehelper分页插件 pom依赖 <?xml version="1.0" encoding="U ...
- spring boot整合mybatis步骤
spring boot整合mybatis步骤 官方说明:MyBatis-Spring-Boot-Starter will help you use MyBatis with Spring Boot 其 ...
- Spring Boot整合MyBatis
最近项目原因可能会继续开始使用MyBatis,已经习惯于spring-data的风格,再回头看xml的映射配置总觉得不是特别舒服,接口定义与映射离散在不同文件中,使得阅读起来并不是特别方便. Spri ...
- Spring Boot基础学习笔记06:Spring Boot整合MyBatis
文章目录 零.学习目标 1.了解Spring Boot数据访问概述 2.掌握使用注解的方式整合MyBatis 3.掌握使用配置文件的方式整合MyBatis 一.Spring Boot数据访问概述 二. ...
- Spring Boot 整合MyBatis(23)
Spring Boot 整合MyBatis Spring Boot 整合 Druid 引入依赖 配置 application.yml pring Boot 整合 tk.mybatis 引入依赖 配置 ...
- Spring Boot 整合 MyBatis Plus实现多数据源的两种方式
第一种:使用配置类的方式: 项目结构 xml依赖: <?xml version="1.0" encoding="UTF-8"?> <proje ...
最新文章
- Linux内存初始化(一)
- 7-22 堆栈模拟队列 (25 分)
- 微信小程序-设置启动页面
- 日本社交餐厅评论服务平台Retty获1050万美元D轮融资
- 星期三,今天早上上了四节JS课程,下午听健康讲座,晚上装系统
- CentOS 7 启动与切换图形界面
- iOS利用SDWebImage实现缓存的计算与清理
- 智能会议系统(16)---Linphone配置大全
- php中的数据库操作和字符串操作session与cookie操作,PHP的cookie与session原理及用法详解...
- Latex英文论文模板汇总(elsevier、arXiv、IEEE Access)
- Android事件机制深入探讨(一)
- 使用python控制其他软件运行并操作处理数据_Python 运行其他程序
- 惠普打印机扫描软件安装
- 【采用】社交网络分析与金融反欺诈应用(知识图谱?)
- roc曲线spss怎么做_如何用SPSS做ROC曲线分析?看这1篇就够了!
- openharmony容器组件之Panel
- 1124 Raffle for Weibo Followers
- t3插密码狗不显示服务器,登陆T3时,用户名和账套都不显示,显示没有检测到合法的LISENCE,需要重新注册密码狗,在注册社区后,搜索.cjt的文件,搜不到...
- 【软考系统架构设计师】第八章 Web架构(知识点必知必会)
- XSLT 是什么类型的语言?
热门文章
- python 车牌识别简单_智能车牌识别 停车如此简单
- ubuntu mysql允许远程连接mysql_ubuntu下允许mysql远程连接
- android fastjson漏洞_亲手带你 Debug Fastjson 的安全漏洞
- java什么时会出现gc_面试题:java GC发生在会么时候,对什么东西,做了什么事情...
- 微软服务器应用软件,HTTP 服务器示例应用程序
- php方法中有%3cbr%3e报错,ecmall 标签以及格式化代码
- Pycharm快捷键及一些常用设置
- myecplise 添加svn插件
- kill_mysql_sleep_thread
- PCA和白化练习之处理二维数据