SpringBoot之Mybatis整合实战(附分页使用)
最近闲下来,写下springBoot与Mybatis的整合教程,希望对大家有所帮助吧,把自己搭建的过程分享给大家。话不多说,开始吧!
使用IDEA自带的Spring Initializr初始化所需要的模块,如下图:


具体pom.xml配置主要如下:


随后配置yml文件指定抽象Mapper接口,用于实现生成的Mapper继承改Mapper实现通用Mapper

目录结构如下:

下面介绍下IDEA MBG(myBatis generator插件的安装破解方式,mybatis plugin收费,需要自行破解),
下面附上破解教程:
Intellij IDEA Mybatis plugin插件破解安装
Mybatis Plugin插件功能
提供Mapper接口与配置文件中对应SQL的导航
编辑XML文件时自动补全
根据Mapper接口, 使用快捷键生成xml文件及SQL标签
ResultMap中的property支持自动补全,支持级联(属性A.属性B.属性C)
快捷键生成@Param注解
XML中编辑SQL时, 括号自动补全
XML中编辑SQL时, 支持参数自动补全(基于@Param注解识别参数)
自动检查Mapper XML文件中ID冲突
自动检查Mapper XML文件中错误的属性值
支持Find Usage
支持重构从命名
支持别名
自动生成ResultMap属性
快捷键: Option + Enter(Mac) | Alt + Enter(Windows)
总之,Mybatis plugin就是一款可以让你的编程效率加倍的工具,像写代码一样写sql和Mybatis文件。
安装步骤
土豪方式安装:
进入Ctrl + ALT+S进入Intellij配置,选择plugins,搜索mybatis plugin,选择安装,如下图:

安装完成,重启Intellij。重新进入Intellij之后会提示输入激活码。当然,激活码是需要购买了。到此土豪安装模式完成。
破解安装
(1)本地安装。
通过以下地址下载mybatis plugin插件:https://plugins.jetbrains.com/plugin/7293-mybatis-plugin
选择对应的版本,进行下载。
下载破解替换文件:https://github.com/myoss/profile
在profile/idea/plugin/MybatisPlugin/路面下找到对应上面插件的破解版本。
打开下载的mybatis_plug.zip文件,找到lib下面的mybatis_plug.jar。用压缩文件打卡jar包,会发现里面com包下有seventh7的目录。用破解插件对应的目录替换此目录。保存jar包压缩文件的更改,保存zip文件的更改。
同样进入Intellij plugins插件安装界面,选择From disk,然后选择刚刚修改过的zip文件。安装,重启。
完成破解安装步骤。
(2)插件安装
在土豪安装成功之后,在本地Intellij 安装目录的plugins下面找到mybatis plugins的目录,找到对应的mybatis_plug.jar文件,同样打开替换掉seventh7的目录文件。然后重启,也能达到破解的效果。不过此方式在Intellij IDEA 2016.3版本无效,因为根本无法找到mybatis_plug.jar文件。
到此,Intellij IDEA Mybatis plugin插件破解安装完成。现在可以尽享插件带来的方便和快捷操作。
下面我们接着之前的步骤新建mybatis-generator.xml,设置好生成文件的路径,数据库依赖包,以及依赖插件后,如下图:


接着选中该xml以Maven方式运行

生成如下:


以上我们的MyBatis就已经设置完毕了。接下来我们就通过一个入口来测试下我们的生成文件是否能使用:

注意下面2个注解,
@EnableTransactionManagement //如果mybatis中service实现类中加入事务注解,需要此处添加该注解
@MapperScan("com.rick.blogcore.persistence.mapper") //扫描的是mapper.xml中namespace指向值的包位置
随后运行该单元测试案例顺利执行,我们的整个springBoot与MaBatis就结合完毕了

接下来我们讲解下分页插件的的使用,
细心的同学发现我之间的pom.xml中添加了分页依赖,下面简单介绍下如何使用


运行以上方法就可以实现分页功能了,是不是很简单!
好啦,这次的实战就到这里了。如果大家有不懂的可以关注程序猿之家上详细交流,
源码见:https://github.com/speedhero/HomeBlog.git
