1.在pom.xml文件中添加mybatis和mysql驱动依赖
<!-- mybatis 依赖 start -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- mybatis 依赖 end -->
<!-- mybatis mysql驱动 start -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- mybatis mysql驱动 end -->
2.在application.properties中添加数据源配置
#数据源配置
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = root
3.新建mapper接口
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user limit 10")
List<Map<String,Object>> list();
}
4.使用
@RestController
public class Example {
@Resource
private UserMapper userMapper;
@RequestMapping("/user")
public List<Map<String,Object>> user() {
List<Map<String,Object>> users = userMapper.list();
return users;
}
}
5.mapper扫描配置
可以在Application类中使用@MapperScan注解来指定扫描包的位置
@SpringBootApplication// same as @Configuration @EnableAutoConfiguration @ComponentScan
@MapperScan("com.gfof.base.mapper")
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Application.class);
}
}
6.加入分页插件
maven依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.0.1</version>
</dependency>
在application.java或其他配置bean中配置分页bean
@Bean
PageHelper pageHelper(){
//分页插件
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("reasonable", "true");
properties.setProperty("dialect", "mysql");
properties.setProperty("supportMethodsArguments", "true");
properties.setProperty("returnPageInfo", "check");
properties.setProperty("params", "count=countSql");
pageHelper.setProperties(properties);
//添加插件
new SqlSessionFactoryBean().setPlugins(new Interceptor[]{pageHelper});
return pageHelper;
}
在controller中使用
@RequestMapping("/hello")
public PageInfo home() {
PageHelper.startPage(1,10);
List<Map<String,Object>> phone = userMapper.list();
return new PageInfo(phone);
}