technology-integration全面解析

technology-integration(六)---AOP实

2018-08-24  本文已影响1395人  海苔胖胖

AOP实现分页有什么好处

利用AOP实现分页功能可以达到零代码入侵的目的,只需要在请求方法上传入对应的分页请求数据即可,SQL的编写以及后台业务与分页代码无关。

PageHelper

PageHelper是Mybatis的一款分页插件,利用ThreadLocal实现分页功能。PageHelper先是根据你即将发出的SQL命令获取count值(也就是数据总量),然后获取当前线程上的线程变量进行分页操作。如果你还没有使用过PageHelper,推荐先去敲个代码体验一下

执行流程

  1. 使用aop获取controller方法中分页的相关请求数据PageBean
  2. 将PageBean保存在线程变量中
  3. 使用aop拦截dao方法,调用PageHelper的分页方法(使用两次aop是因为PageHelper只会对即将执行的SQL语句进行分页,假设你要分页的数据是第二顺序执行,这时候则会导致第一顺序执行的SQL语句被分页,而第二顺序执行的SQL语句相反)

业务内容

获取所有商品信息,并分页

编写ProductMapper.xml

//编写获取全部商品的SQL语句
<select id="selectAllProduct" resultMap="BaseResultMap">
    select product_id, product_name, product_price, product_stock, product_type, product_status,product_version
    from t_product
  </select>

编写ProductMapper.java

public interface ProductMapper {
    List<Product> selectAllProduct();
}

编写ProductDao

//PageInfo是PageHelper封装的一个分页信息类,里面存放着详细的分页字段
public interface ProductDao {
    PageInfo<Product> selectAllProductWithPage();
}

@Repository
public class ProductDaoImpl extends BaseDao implements ProductDao {
    @Autowired
    private ProductMapper productMapper;
  
    @Override
    public PageInfo<Product> selectAllProductWithPage() {
        return new PageInfo<>(productMapper.selectAllProduct());
    }

}

编写ProductService

public interface ProductService {
    PageInfo getAllProductWithPage();
}

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductDao productDao;

    @Override
    public PageInfo getAllProductWithPage() {
        return productDao.selectAllProductWithPage();
    }

}

PageBean(分页实体类)

public class PageBean<T> {
    // 当前页
    private Integer currentPage = 1;
    // 每页显示的总条数
    private Integer pageSize = 10;
    // 总条数
    private Integer totalNum;
    // 是否有下一页
    private Integer isMore;
    // 总页数
    private Integer totalPage;
    // 开始索引
    private Integer startIndex;
    // 分页结果
    private List<T> items;

    public PageBean() {
        super();
    }

    public PageBean(Integer currentPage, Integer pageSize, Integer totalNum) {
        super();
        //
        this.currentPage = currentPage;
        this.pageSize = pageSize;
        this.totalNum = totalNum;
        this.totalPage = (this.totalNum+this.pageSize-1)/this.pageSize;
        this.startIndex = (this.currentPage-1)*this.pageSize;
        this.isMore = this.currentPage >= this.totalPage?0:1;
    }

    public PageBean(Integer currentPage, Integer pageSize) {
        this.currentPage = currentPage;
        this.pageSize = pageSize;
    }

    public Integer getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(Integer currentPage) {
        this.currentPage = currentPage;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Integer getTotalNum() {
        return totalNum;
    }

    public void setTotalNum(Integer totalNum) {
        this.totalNum = totalNum;
    }

    public Integer getIsMore() {
        return isMore;
    }

    public void setIsMore(Integer isMore) {
        this.isMore = isMore;
    }

    public Integer getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(Integer totalPage) {
        this.totalPage = totalPage;
    }

    public Integer getStartIndex() {
        return startIndex;
    }

    public void setStartIndex(Integer startIndex) {
        this.startIndex = startIndex;
    }

    public List<T> getItems() {
        return items;
    }

    public void setItems(List<T> items) {
        this.items = items;
    }
}

编写Controller

Controller方法中使用了PageBean接收分页参数或者使用restful风格接收参数,这里并没有限制你必须这么接收,不过你怎么接收分页参数的就需要在aop中怎么拦截并获取

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @PostMapping("/all")
    public Result getAllProductWithPage(@RequestBody PageBean pageBean) {
        PageInfo pageInfo = productService.getAllProductWithPage();
        return Result.success(pageInfo);
    }

    @GetMapping("/all/{currentPage}/{pageSize}")
    public Result getAllProduct2WithPage(@PathVariable int currentPage,@PathVariable int pageSize) {
        PageInfo pageInfo = productService.getAllProductWithPage();
        return Result.success(pageInfo);
    }
}

编写PageHelperAOP类


@Component
@Aspect
public class PageHelperAop {

    private static final Logger log = LoggerFactory.getLogger(PageHelperAop.class);

    private static final ThreadLocal<PageBean> pageBeanContext = new ThreadLocal<>();

    //以WithPage结尾的Controller方法都是需要分页的方法
    @Before(value = "execution(* com.viu.technology.controller..*.*WithPage(..))")
    public void controllerAop(JoinPoint joinPoint) throws Exception {
        log.info("正在执行PageHelperAop");
        PageBean pageBean =null;

        Object[] args = joinPoint.getArgs();

        //获取类名
        String clazzName = joinPoint.getTarget().getClass().getName();
        //获取方法名称
        String methodName = joinPoint.getSignature().getName();
        //该方法通过反射获取参数列表
        Map<String,Object > nameAndArgs = this.getFieldsName(this.getClass(), clazzName, methodName,args);

        pageBean=(PageBean) nameAndArgs.get("pageBean");

        if (null == pageBean) {
            pageBean = new PageBean();
            pageBean.setCurrentPage((Integer) nameAndArgs.get("currentPage"));
            pageBean.setPageSize((Integer) nameAndArgs.get("pageSize"));
        }

        //将分页参数放置线程变量中
        pageBeanContext.set(pageBean);

    }

    @Before(value = "execution(* com.viu.technology.dao..*.*WithPage(..))")
    public void daoAop(JoinPoint joinPoint) throws Exception {
        PageBean pageBean = pageBeanContext.get();
        PageHelper.startPage(pageBean.getCurrentPage(), pageBean.getPageSize());
    }

    private Map<String,Object> getFieldsName(Class cls, String clazzName, String methodName, Object[] args) throws Exception {
        Map<String,Object > map=new HashMap<String,Object>();

        ClassPool pool = ClassPool.getDefault();
        ClassClassPath classPath = new ClassClassPath(cls);
        pool.insertClassPath(classPath);

        CtClass cc = pool.get(clazzName);
        CtMethod cm = cc.getDeclaredMethod(methodName);
        MethodInfo methodInfo = cm.getMethodInfo();
        CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
        LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
        if (attr == null) {
            // exception
        }
        int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
        for (int i = 0; i < cm.getParameterTypes().length; i++){
            map.put( attr.variableName(i + pos),args[i]);
        }
        return map;
    }

}

PostMan测试

请提前导入相关数据

使用JSON请求会自动将json转换为PageBean实体类,请注意json字段名需和实体类保持一致


image.png
image.png

异步调用dao导致分页失败方法

由于异步调用导致子线程无法访问主线程的线程变量,导致PageHelper分页失败
所以你就老老实实的传参,然后调用PageHelper.startPage方法吧,哈哈哈,88

public PageInfo asyncGetAllProductWithPage(int currentPage,int pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        return productDao.selectAllProductWithPage();
    }

更多文章请关注该 technology-integration全面解析专题

上一篇下一篇

猜你喜欢

热点阅读