Spring Boot 整合 TKMybatis 二次简化持久层代码的实现
经常用MyBatis的的都知道,使用这个框架存在一个非常不友善的问题就是,就是每操作一个单表就需要自己手写一个xml文件,虽然说可以用工具生成xml和实体类可以解决这个问题,但是二次开发的时候对某个表字段进行修改的时候,生成xml文件就不现实啦。最近发现tk.mybatis就非常好的解决了这个问题。tk.mybatis整合了MyBatis框架,在其基础上提供了很多工具,封装了常用的增删改查SQL语句,可以让我们的开发效率更高。在这里和大家分享一下。
引入依赖
在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#MySQL8.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接口的扫描路径
importorg.springframework.boot.SpringApplication;
importorg.springframework.boot.autoconfigure.SpringBootApplication;
importtk.mybatis.spring.annotation.MapperScan;
@MapperScan(value="com.antoniopeng.springboot.mybatis.mapper")
@SpringBootApplication
publicclassHelloSpringBootMybatisApplication{
publicstaticvoidmain(String[]args){
SpringApplication.run(HelloSpringBootMybatisApplication.class,args);
}
}
整合PageHelper分页插件
引入依赖
在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
publicclassMyBatisTests{
@Autowired
UserServiceuserService;
/**
*测试分页插件
*/
@Test
publicvoidtestPageHelper(){
Exampleexample=newExample(User.class);
//查询条件
example.createCriteria().andEqualTo("userId","1")
//分页参数
PageHelper.startPage(1,10,"create_timedesc");
//获取分页列表数据
ListuserList=userService.selectByExample(example);
PageInfopageInfo=newPageInfo(userList);
//获取列表总数
intuserCount=(int)pageInfo.getTotal();
}
}
到此这篇关于SpringBoot整合TKMybatis二次简化持久层代码的实现的文章就介绍到这了,更多相关SpringBoot整合TKMybatis内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!