package com.persagy.dmp.mybatis.config;

import com.baomidou.mybatisplus.autoconfigure.MybatisPlusPropertiesCustomizer;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;

/**
 * MybatisPlus公共配置
 * @author lixing
 * @description 由 Mybatisplus Code Generator 创建
 * @since 2020-09-09 09:13:27
 **/
@MapperScan(value = "com.persagy.**.dao")
@Configuration
@EnableTransactionManagement
public class MybatisPlusConfig implements CommandLineRunner {

    @Resource
    private ObjectMapper objectMapper;
    @Value("${persagy.common.sql.limit:500}")
    private long sqlLimit;

    @Override
    public void run(String... args) throws Exception {
        // 注入objectMapper，处理Java对象转JsonString
        JacksonTypeHandler.setObjectMapper(objectMapper);
    }

    /**
     * 注册分页插件
     * 使用示例： IPage<Member> memberPage = new Page<>(1, 2，false) true查询总记录数量
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor interceptor = new PaginationInterceptor();
        // 设置每页查询记录上限，默认500（与mp相同）
        interceptor.setLimit(sqlLimit);
        return interceptor;
    }

    /**
     * 自动扫描typeHandlers
     * @return
     */
    @Bean
    public MybatisPlusPropertiesCustomizer mybatisPlusPropertiesCustomizer() {
        return properties -> properties.setTypeHandlersPackage("com.persagy.**.typehandler");
    }
}
