springboot整合mybatis

整合mybatis

1. 引入依赖

使用mybatis逆向工程生成dao, domain, mapper, 等配置,放入项目中.

<!-- pagehelper分页插件 -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.3</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.35</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.0</version>
</dependency>
2, 配置数据源

只需要在properties文件中配置相关内容即可

# 数据库连接设置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# 连接池配置
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-active=20
3, 测试查询
@Log4j2
@RestController
public class BonusInfoController {

    // private Logger logger = LogManager.getLogger(BonusInfoController.class);

    @Resource
    private BonusInfoService bonusInfoService;

    @RequestMapping("/bonusInfo")
    public String reqTest(String reqStr) {

        log.info("测试收到参数: {}", reqStr);

        GoBonusInfo bonusInfo = bonusInfoService.getBonusInfoByTransId(reqStr);

        log.info("查询返回: {}", JSON.toJSONString(bonusInfo));
        return JSON.toJSONString(bonusInfo);
        // return "ok";
    }
}

// 测试返回结果正确

4, 测试分页

properties文件增加配置

# 配置分页插件 使用数据库
pagehelper.helper-dialect=mysql
@RequestMapping("/pageTest")
public String pageTest(String mchId) {
    log.info("收到参数;{}", mchId);
    List<GoBonusInfo> bonusInfoList = bonusInfoService.getBonusInfoByMchId(mchId);
    log.info("第一次查询:{}", bonusInfoList.size());
    PageHelper.startPage(1, 2);
    List<GoBonusInfo> bonusInfoList2 = bonusInfoService.getBonusInfoByMchId(mchId);
    PageInfo<GoBonusInfo> pageInfo = new PageInfo<>(bonusInfoList2);
    log.info("第二次查询:{}, {}, {}", pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getPageNum());
    log.info(JSON.toJSONString(pageInfo.getList()));
    return "ok";
}
// 测试返回结果正确

   转载规则


《springboot整合mybatis》 liuzhihang 采用 知识共享署名 4.0 国际许可协议 进行许可。
  目录