spring boot使用(二) 整合mybatis

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);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值