Springboot整合mybatis
总结步骤:
1,导入依赖
2,配置文件
3,编写配置类-配置分页
4,启动类上加注解扫描mapper
1,导入依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.0</version>
</dependency>
2,导入依赖
mybatis: # mybatis配置
mapper-locations: classpath:mappers/**/*.xml
# 指定自动扫描生成类型别名的 Java 类所在的包
type-aliases-package: com.xzq.mybatis.domain.entity
# 配置驼峰命名映射
configuration:
map-underscore-to-camel-case: true #自动驼峰映射
default-fetch-size: 100
default-statement-timeout: 30
3,编写配置类-配置分页
package com.xzq.mybatis.config;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.util.Properties;
@Configuration
public class MyBatisConfig {
@Autowired
private SqlSessionFactory sqlSessionFactory;
@PostConstruct
public void initPageHelper() {
Interceptor pageHelperInterceptor = new PageHelper();
Properties properties = new Properties();
properties.setProperty("helperDialect", "mysql");
properties.setProperty("reasonable", "true");
properties.setProperty("supportMethodsArguments", "true");
properties.setProperty("params", "count=countSql");
// 设置拦截器属性
pageHelperInterceptor.setProperties(properties);
// 添加拦截器到SqlSessionFactory的配置
sqlSessionFactory.getConfiguration().addInterceptor(pageHelperInterceptor);
}
}
4,启动类上加注解扫描mapper
com.xzq.mybatis.mapper:mapper接口相对路径
@SpringBootApplication
@MapperScan(basePackages = "com.xzq.mybatis.mapper")
public class ApplicationStarter {
public static void main(String[] args) {
SpringApplication.run(ApplicationStarter.class,args);
}
}
分页的使用:
注意点:分页紧紧只对最靠前的一个sql查询有效,比如第一个 PageHelper.startPage()只对 perdMapper.selectPerd2q();分页有效,如果想要第二个perdMapper.selectPerd()分页有效,则需要前面在加上PageHelper.startPage();因为PageHelper.startPage(1,1)不会全局分页有效
PageHelper.startPage(1,1);
List<Team> perds = perdMapper.selectPerd2q();
PageHelper.startPage(1,1);
List<Perd> perdList = perdMapper.selectPerd();