3步实现SpringBoot和MyBatis集成
2020-12-06 本文已影响0人
V哥带你写程序
被SpringBoot的简单所折服,与MyBatis集成是如此简单。
我使用的数据库是MySQL
集成步骤
- 引入mybatis和mysql jdbc驱动的jar包
- 配置数据源和Mapper位置
- 代码中使用mybatis的mapper查询数据库
一、POM中加入jar引用
引入mybatis的springboot starter
引入mysql最新版的驱动
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
就上面两个,其他的不需要
二、配置数据源和Mapper位置
Mybatis支持把SQL写在Java注解中,其实这样Java代码会看起来比较乱,所以我还是喜欢把SQL分开放在XML中。 Mapper的XML文件都放在了resources/mappers目录下。
# MySQL数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/rcdb?autoReconnect=true&failOverReadOnly=false&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai
spring.datasource.username=rc_user
spring.datasource.password=igYmICMVRX1HnIwt
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 指定Mybatis XML文件夹位置
mybatis.mapper-locations=classpath:mappers/*.xml

三、代码中使用Mapper
Controller中通过@Resource注解注入userMapper, 在login方法中用到userMapper查询用户是否存在。

Controller中使用@Resource注解代替@Autowired注解来注入userMapper. 避免IDEA提示找不到userMapper bean.
上面的登录代码还不完善,只为了测试springboot和mybatis的集成。
Mapper代码
现在只有一个方法,到数据库中按用户名查询用户。

mapper的xml

就这么简单
彩蛋 Free MyBatis 插件
实际开发中mapper会有很多的方法,到对应的xml文件中去找对应的SQL语句是比较繁琐的。一天要按N多遍 Ctrl + F。一位叫 吴志展 的同行提供了一款 Free MyBatis Plugin, 下载量过百万。 安装之后Mapper方法旁边出现绿色小箭头,可以在Mapper方法和XML中快速切换。

安装后重启IDEA生效

点击这个绿色箭头就可以在Java代码和XML中快速切换了。