本章内容基于SpringBoot入门:https://www.cnblogs.com/forelim/p/15379580.html
SpringBoot整合Mybatis
-
导入依赖
<!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.26</version> </dependency> <!-- mybatis启动器 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency> <!-- 测试 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <!-- 分页插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency>
-
加载配置 application.yml
# 端口号 server: port: 8080 # 数据源 spring: datasource: # 驱动 driver-class-name: com.mysql.cj.jdbc.Driver # 路径 url: jdbc:mysql://localhost:3306/demo?useSSL=false&characterEncoding=utf-8&serverTimezone=Asia/Shanghai # 用户名 username: root # 密码 password: mysql # mybatis配置 mybatis: configuration: # 日志 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 下划线转驼峰 map-underscore-to-camel-case: true # 别名包 type-aliases-package: com.demo.entity # 映射文件位置 mapper-locations: classpath:mapper/*.xml # 分页插件 pagehelper: # 数据库 helper-dialect: mysql # 合理化 reasonable: true # 支持通过方法传递参数 support-methods-arguments: true # 参数 params: count==countSql # 传入0时显示全部数据 page-size-zero: true
-
Entity & Mapper
public class Demo { private Integer id; private String name; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
import com.demo.entity.Demo; import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper // 如果mapper接口过多 可以在主启动类上加上@MapperScan("mapper接口包") 代替 @Mapper注解 public interface DemoMapper { /** * 查询全部 * @return 列表 */ List<Demo> list(); }
<?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="com.demo.mapper.DemoMapper"> <select id="list" resultType="demo"> select id, name, age from t_demo </select> </mapper>
-
测试类
import com.demo.entity.Demo; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; @SpringBootTest public class DemoMapperTest { /** * 自动织入mapper接口 */ @Autowired private DemoMapper demoMapper; @Test void list() { // 分页 PageHelper.startPage(1,2); // 调用 List<Demo> list = demoMapper.list(); // 封装分页对象 PageInfo<Demo> demoPageInfo = new PageInfo<>(list); } }
-
成功!