springboot整合第三方框架--mybatis --pageHelper

231 阅读1分钟

springboot整合mybatis

1.依赖

<!--mysql的依赖-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

<!--mybatis启动依赖:DataSourceAutoConfiguration:读取application配置文件中以spring.datasource -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.2</version>
</dependency>

2.配置文件

#数据源信息
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#characterEncoding防止您添加到数据库的数据出现乱码
spring.datasource.url=jdbc:mysql://localhost:3306/qy165?serverTimezone=Asia/Shanghai&characterEncoding=UTF8
spring.datasource.username=root
spring.datasource.password=123456

#指定mybatis映射文件的路径  classpath是编译后的路径
mybatis.mapper-locations=classpath:mapper/*.xml

#控制台打印sql日志
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

(3)创建实体类和dao接口 @Mapper @MapperScan(baskPackages=""需要扫描的映射路径)

@MapperScan(baskPackages=""需要扫描的映射路径) 用来扫描指定包下的 Mapper 接口,将其构造成实体类并加入到 Spring 容器中,使得这些 Mapper 接口能够通过 @Autowired 注解直接注入到代码中使用

@Mapper和上方的用法相同,只不过是加载dao层的类上,一次注入一个指定的dao类

@Data
public class Product {

    Integer pid;
    String pname;
    Double price;
    String pdesc;
    Integer pflag;
    }
@Mapper
public interface ProductDao {
        public List<Product> findAll();
}

sql语句

image.png

image.png

测试

@SpringBootTest
class SpringBoot01ApplicationTests {
    @Autowired
    private ProductDao productDao;
    @Test
    void contextLoads() {
        productDao.findAll().stream().forEach(System.out::println);
    }
}

springboot整合pageHelper

依赖

<!--pageHelper分页插件-->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.4.6</version>
</dependency>

测试代码

@SpringBootTest
class SpringBoot01ApplicationTests {
    @Autowired
    private ProductDao productDao;
    @Test
    void contextLoads() {
        PageHelper.startPage(2,3);
        List<Product> all = productDao.findAll();
        PageInfo<Product> pageInfo = new PageInfo<>(all);
        final int pages = pageInfo.getPages();
         long total = pageInfo.getTotal();
        System.out.println("总页数++++"+pages);
        System.out.println("总条数数++++"+total);
        System.out.println("pageInfo++++"+pageInfo);
        List<Product> list = pageInfo.getList();
        list.stream().forEach(System.out::println);
    }
}