Mybaits JavaBean配置

2020-03-09  本文已影响0人  忘记_3a6a


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.apache.ibatis.session.ExecutorType;
import org.springframework.context.annotation.Bean;
import org.apache.ibatis.session.Configuration;
import java.util.Properties;


@org.springframework.context.annotation.Configuration
public class MybatisConfig {


    @Bean
    public PageHelper pageHelper(){
        PageHelper pageHelper = new PageHelper();
        //添加配置,也可以指定文件路径
        Properties p = new Properties();
        p.setProperty("offsetAsPageNum", "true");
        p.setProperty("rowBoundsWithCount", "true");
        p.setProperty("reasonable", "true");
        pageHelper.setProperties(p);
        return pageHelper;
    }

    @Bean
    public Configuration mybatisConfiguration()
    {
        Configuration configuration = new Configuration();
        // 全局映射器启用缓存
        configuration.setCacheEnabled(false);
        // 查询时,关闭关联对象即时加载以提高性能
        configuration.setLazyLoadingEnabled(false);
        // 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果
        configuration.setMultipleResultSetsEnabled(true);
        // 允许使用列标签代替列名
        configuration.setUseColumnLabel(true);
        // 给予被嵌套的resultMap以字段-属性的映射支持 FULL,PARTIAL
        configuration.setAutoMappingBehavior(AutoMappingBehavior.PARTIAL);
        // 对于批量更新操作缓存SQL以提高性能 BATCH,SIMPLE,设置为BATCH有个缺陷就是无法获取update、delete返回的行数
        configuration.setDefaultExecutorType(ExecutorType.SIMPLE);
        // 允许在嵌套语句上使用行边界。如果允许,设置false。
        configuration.setSafeRowBoundsEnabled(false);
        // 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能
        configuration.setAggressiveLazyLoading(false);
        // 数据库超过30秒仍未响应则超时
        configuration.setDefaultStatementTimeout(30);
        //驼峰命名,如果不进行配置,数据库中有下划线的字段是不可以转换成驼峰命名的
        configuration.setMapUnderscoreToCamelCase(true);

        // 添加分页拦截器
        configuration.addInterceptor(pageInterceptor());
        return configuration;
    }

    @Bean
    public PageInterceptor pageInterceptor()
    {
        //配合PageHelpder使用
        Properties properties = new Properties();
        properties.setProperty("helperDialect", "mysql");
        // 设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用 ,
        // 和startPage中的pageNum效果一样
        properties.setProperty("offsetAsPageNum", "false");
        // 设置为true时,使用RowBounds分页会进行count查询
        properties.setProperty("rowBoundsWithCount", "true");
        // 设置为true时,如果pageSize=0或者RowBounds.limit = 0就会查询出全部的结果
        properties.setProperty("pageSizeZero", "true");
        // 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页,禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据
        properties.setProperty("reasonable", "false");

        PageInterceptor pi = new PageInterceptor();
        pi.setProperties(properties);
        return pi;
    }




}

上一篇下一篇

猜你喜欢

热点阅读