一、介绍
SpringBoot有两种方法与数据库建立连接,一种是集成Mybatis,另一种用JdbcTemplate,本文主要讨论集成Mybatis方式。
SpringBoot整合Mybatis也有两种方式,分别为XML配置方式和注解方式,主要优势点如下:
XML配置方式:隔离sql和业务代码,清晰表达sql,尤其对于较长的sql。
注解方式:代码更加精简,方便。
本文主要讨论XML配置方式,后续文章讨论注解方式。
二、SpringBoot整合Mybatis连接Mysql数据库
1、添加MySQL 连接驱动依赖、SpringBoot Mybatis 依赖,完整pom文件如下:
4.0.0
com.example
demo
1.0.0
jar
hello
Demo project for Spring Boot
1.3.0
5.1.39
org.springframework.boot
spring-boot-starter-parent
2.1.1.RELEASE
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
${mysql-connector}
org.mybatis.spring.boot
mybatis-spring-boot-starter
${mybatis-spring-boot}
org.projectlombok
lombok
ch.qos.logback
logback-classic
org.slf4j
jcl-over-slf4j
注:
整合MyBatis的核心依赖MyBatis-Spring-Boot-Starter提供:
自动检测现有的DataSource
将创建并注册SqlSessionFactory的实例,该实例使用SqlSessionFactoryBean将该DataSource作为输入进行传递
将创建并注册从SqlSessionFactory中获取的SqlSessionTemplate的实例。
自动扫描您的mappers,将它们链接到SqlSessionTemplate并将其注册到Spring上下文,以便将它们注入到您的bean中。
因此,引入该Starter之后,只需要定义一个DataSource即可(application.properties中可配置),它会自动创建使用该DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。会自动扫描你的Mappers,连接到SqlSessionTemplate,并注册到Spring上下文中。
2、配置application.yml文件
配置数据库连接信息(数据源)
spring:
#数据源
datasource:
url: jdbc:mysql://localhost:3306/springbootdb??useUnicode=true&characterEncoding=UTF-8
username: root
password: 123
driver-class-name: com.mysql.jdbc.Driver
配置mybatis
#mybatis配置
mybatis:
typeAliasesPackage: com.example.mybaitsxml.dao.entity
mapperLocations: classpath:mapper/*.xml
#configLocation: classpath:/mybatis-config.xml
注:通常,若mybatis配置信息较少,只是针对基本配置无需复杂配置,则只需在application.yml文件中配置即可,否则最好配置在 mybatis-config.xml中。
缺少mapperLocations配置,出现报错:
There was an unexpected error (type=Internal Server Error, status=500).
Invalid bound statement (not found): com.example.mybatis.cache.dao.mapper.***
3、代码实现
demo工程文件结构:
controller层
@Slf4j
@RestController
@RequestMapping("/web")public classUserController {
@AutowiredprivateUserService userService;
@GetMapping("/queryAllUsers")public ListqueryAllUsers(){returnuserService.queryAllUsers();
}
}
service层(实现)
@Slf4j
@Servicepublic class UserServiceImpl implementsUserService {
@AutowiredprivateUserMapper userMapper;
@Overridepublic ListqueryAllUsers() {
log.info("/queryAllUsers start...");returnuserMapper.queryAllUsers();
}
}
dao层
dao层分为数据库实体类(entity)和数据库操作mapper接口(mapper)
entity:
@Datapublic classUser {privateString name ;privateString sex;privateInteger age;privateInteger classNo;
}
mapper:
public interfaceUserMapper {
ListqueryAllUsers();
}
mapper.xml实现
select
name_,
sex,
age,
class_no
from
tbl_user
4、执行效果
5、Demo源码
本文示例源码已托管到本人Github仓库,有需要的朋友请自行拉取。