SpringBoot- xml方式整合Mybatis
Posted 永旗狍子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot- xml方式整合Mybatis相关的知识,希望对你有一定的参考价值。
SpringBoot整合Mybatis
一.xml方式整合mybatis
xml方式在编写复杂SQL时,更适合。
1.导入依赖
<!-- mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- druid连接-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!-- mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
2.编写配置文件
//准备实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Air {
private Integer id;
private Integer districtId;
private java.sql.Date monitorTime;
private Integer pm10;
private Integer pm25;
private String monitoringStation;
private java.sql.Date lastModifyTime;
@Override
public String toString() {
return "Air{" +
"id=" + id +
", districtId=" + districtId +
", monitorTime=" + monitorTime +
", pm10=" + pm10 +
", pm25=" + pm25 +
", monitoringStation='" + monitoringStation + '\\'' +
", lastModifyTime=" + lastModifyTime +
'}';
}
}
3.准备Mybatis
3.1接口
@ComponentScan
public interface AirMapper {
List<Air> selectAll();
}
3.2在启动类中,添加直接扫描Mapper接口所在的包
@SpringBootApplication
@MapperScan(basePackages = "boot.mapper")
public class Springboot02Application {
public static void main(String[] args) {
SpringApplication.run(Springboot02Application.class, args);
}
}
3.3准备映射文件
<?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="boot.mapper.AirMapper">
<!-- List<Air> selectAll();-->
<select id="selectAll" resultType="boot.entity.Air">
select * from air
</select>
</mapper>
3.4 yml文件
<!-- 添加yml文件配置信息 -->
# mybatis配置
mybatis:
# 扫描映射文件
mapper-locations: classpath:mapper/*.xml
# 配置别名扫描的包
type-aliases-package: com.qf.firstspringboot.entity
configuration:
# 开启驼峰映射配置
map-underscore-to-camel-case: true
# 连接数据库的信息
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql:///air?serverTimezone=UTC
username: root
password: 123
type: com.alibaba.druid.pool.DruidDataSource
4.测试
@SpringBootTest
class AirMapperTest {
@Autowired
private AirMapper airMapper;
@Test
void selectAll() {
List<Air> airs = airMapper.selectAll();
for (Air air : airs) {
System.out.println(air);
}
}
}
以上是关于SpringBoot- xml方式整合Mybatis的主要内容,如果未能解决你的问题,请参考以下文章
SpringBoot整合Mybatis方式1:使用XML方式整合Mybatis(添加数据修改数据删除数据查询数据)
SpringBoot整合Dubbo的第三种方式——XML配置 + @ImportResource
springboot使用之二:整合mybatis(xml方式)并添加PageHelper插件
SpringBoot整合Dubbo的第三种方式——XML配置 + @ImportResource