首页 > 代码库 > springboot mybatis 集成mapper与pagehelper
springboot mybatis 集成mapper与pagehelper
1、引入jar到pom.xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.0</version>
</dependency>
2、配置mapper
创建application-bean.xml,文件内容如下
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 注入spring boot无法扫描到的bean. -->
<bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="http://www.mamicode.com/study.boot.config。MyMapper" />
<property name="properties">
<value>
mappers=tk.mybatis.mapper.common.Mapper
</value>
</property>
</bean>
</beans>
3、创建配置类
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ImportResource(value=http://www.mamicode.com/{"classpath:application-bean.xml"})
public class ConfigClass {
}
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.github.pagehelper.PageHelper;
@Configuration
public class MyBatisConfiguration {
private static final Logger logger = LoggerFactory.getLogger(MyBatisConfiguration.class);
@Bean
public PageHelper pageHelper() {
logger.info("注册MyBatis分页插件PageHelper");
PageHelper pageHelper = new PageHelper();
Properties p = new Properties();
p.setProperty("offsetAsPageNum", "true");
p.setProperty("rowBoundsWithCount", "true");
p.setProperty("reasonable", "true");
pageHelper.setProperties(p);
return pageHelper;
}
}
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
}
4、实际运用
mybatis的mapper继承通用mapper
@Mapper
public interface CityMapper extends MyMapper<City>{
}
直接使用
@RestController
@RequestMapping("/boot")
public class HelloWorld {
@Autowired
CityMapper cityMapper;
@RequestMapping("/hello")
public List<City> greeting() {
PageHelper.startPage(1, 5);
return cityMapper.selectAll();
}
}
springboot mybatis 集成mapper与pagehelper