自学内容网 自学内容网

Spring Boot 整合Mybatis-Plus联表分页查询

1.什么是Mybatis-plus?

Mybatis-plus是一个Mybatis的增强工具,在mybatis的基础上只做增强不做改变,提高效率。

引入mybatis-plus依赖:有了mybatis-plus依赖可以不加mybatis依赖

 <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.7</version>
        </dependency>

连接数据库

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/company?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root

添加映射文件路径

mybatis-plus.mapper-locations=classpath:mapper/*.xml

添加日志:方便查询错误

mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

添加分页查询

@Configuration
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor mybatisPage = new MybatisPlusInterceptor();
        mybatisPage.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return mybatisPage;
    }
}

实体类正常

@Data
@ApiModel(value = "员工类")
public class Worker  {
    @ApiModelProperty("员工编号")
    @TableId(type = IdType.AUTO)//id自增
    private Integer id;
    @ApiModelProperty("员工姓名")
    private String name;
    @ApiModelProperty("员工性别")
    private String sex;
    @ApiModelProperty("员工工资编号")
    private Integer salary;
    @ApiModelProperty("员工是否入党")
    private String party;
    @ApiModelProperty("员工入职时间")
  @JsonFormat(pattern ="yyyy-MM-dd",timezone = "GMT+8")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date inTime;
    @ApiModelProperty("员工地址")
    private String origin;
    @ApiModelProperty("员工部门编号")
    @TableField(value = "dep")
    private Integer depid;
    @TableField(exist = false)
    private Dep dep;

}

dao

public interface WorkerMapper extends BaseMapper<Worker> {
    int addWorker(Worker worker);
    int update(Worker worker);
    int delete(int id);
    Worker selectById(int id);
    List<Worker> selectAll();
//    分页查询
    IPage<Worker> selectByPage(IPage<Worker> page, @Param("p")Wrapper<Worker> queryWrapper);
}

mapper.xml

    <select id="selectByPage" resultMap="myMap">
        select*from worker w join dep d on d.id=w.dep ${p.customSqlegment}
    </select>

测试

@SpringBootTest
class SpringbootApplicationTests {
@Autowired
private WorkerMapper workerMapper;
    @Test
    void selectPage() {
        Page<Worker> page = new Page<>(1, 2);
        IPage<Worker> page1 = workerMapper.selectByPage(page, null);
        System.out.println("总页数"+page1.getPages());
        System.out.println("总条数"+page1.getTotal());
        System.out.println("当前页的记录"+page1.getRecords());
    }

}

原文地址:https://blog.csdn.net/R202471/article/details/140434275

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!