引入依赖
在 pom.xml 中引入 mapper-spring-boot-starter 依赖
com.alibaba druid-spring-boot-starter 1.1.10 mysql mysql-connector-java 5.1.40 runtime tk.mybatis mapper-spring-boot-starter 2.0.2
在 application.yml 中添加相关配置
spring: datasource: druid: url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8&useSSL=false username: root password: 123456 initial-size: 1 min-idle: 1 max-active: 20 test-on-borrow: true driver-class-name: com.mysql.jdbc.Driver # MySQL 8.x: com.mysql.cj.jdbc.Driver mybatis: type-aliases-package: # 实体类的存放路径,如:com.antoniopeng.hello.spring.boot.entity mapper-locations: classpath:mapper/*.xml # mapper.xml 文件存放路径,这里存放在配置文件目录 resources 下 logging: level: com.antoniopeng.hello.springboot.mybatis: debug # 配置监听日志
在 Application 入口类中使用 tk.mybatis.spring.annotation 包下的 @MapperScan 注解指定 Mapper 接口的扫描路径
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;
@MapperScan(value = "com.antoniopeng.springboot.mybatis.mapper")
@SpringBootApplication
public class HelloSpringBootMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(HelloSpringBootMybatisApplication.class, args);
}
}引入依赖
在 pom.xml 中引入 pagehelper-spring-boot-starter 依赖
com.github.pagehelper pagehelper-spring-boot-starter 1.2.5
分页查询示例
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@Transactional
@Rollback
public class MyBatisTests {
@Autowired
UserService userService;
/**
* 测试分页插件
*/
@Test
public void testPageHelper() {
Example example = new Example(User.class);
// 查询条件
example.createCriteria().andEqualTo("userId", "1")
// 分页参数
PageHelper.startPage(1, 10, "create_time desc");
// 获取分页列表数据
List userList = userService.selectByExample(example);
PageInfo pageInfo = new PageInfo(userList);
// 获取列表总数
int userCount = (int) pageInfo.getTotal();
}
}