Step1
在pom.xml中添加依赖
<!-- 加载postgresql驱动 -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.14</version>
</dependency>
<!-- 加载jdbc连接数据库 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- 加载mybatis jar包 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
Step2
application.yml文件中添加配置
spring:
datasource:
#type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: org.postgresql.Driver
url: jdbc:postgresql://xxx.xxx.xxx.xxx:5432/postgres
username: postgres
password: 123456
mybatis:
# 全局配置的文件位置
# config-location: classpath:mybatis-config.xml
# 映射路径
mapper-locations: classpath:mappers/*.xml
# 可以不写配置文件路径 写下面这个 但是上面的全局配置文件和下面这个不能同时存在 否则SpringBoot 不知道解析哪一个
configuration: #指定mybatis全局配置文件中的配置项
map-underscore-to-camel-case: true
Step3
到这一步,MyBatis配置完成,可以试一下是否能成功和数据库连接:
- 创建Controller
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/test")
public Object test(){
userService.test();
return 123;
}
}
- 写Service接口(由于懒所以没有把接口和实现类分开)
@Service