本篇文章给大家分享的是有关TKMybatis 怎么在Spring Boot中使用,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
引入依赖
在 pom.xml
中引入 mapper-spring-boot-starter
依赖
<!-- druid-spring-boot-starter -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!-- 数据库连接依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
<scope>runtime</scope>
</dependency>
<!-- mapper-spring-boot-starter -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.0.2</version>
</dependency>
在 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
依赖
<!-- pagehelper-spring-boot-starter -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
分页查询示例
@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<User> userList = userService.selectByExample(example);
PageInfo pageInfo = new PageInfo(userList);
// 获取列表总数
int userCount = (int) pageInfo.getTotal();
}
}
以上就是TKMybatis 怎么在Spring Boot中使用,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。