MyBatisPlus拦截器简单实现

MyBatisPlus拦截器实现

application.properties开启日志输出

# 应用名称
spring.application.name=springboot_hm
# 数据库配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.couchbase.username=root
spring.datasource.password=123456
#日志输出
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
# 设置表前缀和entry包的Book类结合表示tb_book表
mybatis-plus.global-config.db-config.table-prefix=tb_

创建entry包Book类

package itheima.entry;

public class Book {
          
   
    private Integer id;
    private String name;

    @Override
    public String toString() {
          
   
        return "entry{" +
                "id=" + id +
                ", name=" + name +  +
                };
    }

    public Integer getId() {
          
   
        return id;
    }

    public void setId(Integer id) {
          
   
        this.id = id;
    }

    public String getName() {
          
   
        return name;
    }

    public void setName(String name) {
          
   
        this.name = name;
    }
}

创建dao包下BookDao类

package itheima.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import itheima.entry.Book;
import org.apache.ibatis.annotations.Mapper;

@Mapper
//继承BaseMapper自动完成数据库增删改查的方法
public interface BookDao extends BaseMapper<Book> {
          
   
}

创建config目录下MpConfig类

@Configuration
public class MpConfig{
          
   
	@Bean
	public MybatisPlusInterceptor mpInterceptor(){
          
   
		//定义拦截器
		MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //添加内部拦截器
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
	}
}

测试

@SpringBootTest
class SpringbootHmApplicationTests {
          
   
    @Autowired
    private BookDao bookDao;
    @Test
    void contextLoads() {
          
   
        System.out.println("test....");
        //实现分页效果
        IPage page = new Page(1,5);
        bookDao.selectPage(page,null);
    }

}
经验分享 程序员 微信小程序 职场和发展