Bootstrap

springboot详细整合mybatisplus

SpringBoot详细整合mybatisPlus

无奈,一个小的新项目只有mybatis不习惯,那就来加个plus吧~

一、引入mybatis_plus依赖

     <properties>
   <pagehelper.spring.boot.starter.version>1.4.6</pagehelper.spring.boot.starter.version>
        <mybatisplus.version>3.4.0</mybatisplus.version>
    </properties>

<!-- mybatisPlus  它的分页会与pagehelper分页冲突,目前系统用的pageHelper分页-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatisplus.version}</version>
        </dependency>

        <!-- pagehelper 分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>${pagehelper.spring.boot.starter.version}</version>
        </dependency>

上面有一个注意的点就是mybatis_plus的分页会与pageHelper的分页冲突,因为他们的底层其实差不多的。我个人比较喜欢mybatis_plus的分页 ,因为pageHelper的联表分页会比较麻烦,而mybatis_plus的联表分页只需要在mapper层上面加上@Select注解写联表查询语句就可以了。 但是没办法少数服从多数,这里就用了pageHelper分页。

上面有一点要注意的是,引入了mybatis_plus的依赖后mybatis的依赖就不需要了可以干掉。

二、修改mybatis_plus的yml配置

首先看一下整个项目大概的包的层级,主要是为了映射上mapper和xml文件。

# MyBatis配置
mybatis:
    # 搜索指定包别名
    typeAliasesPackage: com.ruoyi.project.**.domain
    # 配置mapper的扫描,找到所有的mapper.xml映射文件
    mapperLocations: classpath*:mybatis/**/*Mapper.xml
    # 加载全局的配置文件
    configLocation: classpath:mybatis/mybatis-config.xml

#MyBatisPlus配置
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  mapper-locations: classpath*:/mybatis/**/**.xml
  type-aliases-package: com.ruoyi.project.chouzhou

三、添加mybatis_plus的其他配置以及包扫描

下面的两个配置一个是为了分页(当然,其实目前由于与pageHelper冲突就没用plus的分页了,含泪舍弃),另一个则是基础字段的填充和更新。

重要的是添加包扫描,对应你的mapper层的包路径。

ps:plus的删除是逻辑删除只需要在对应的删除标识字段上机上@TableLogic注解,查询的时候根据改字段筛选就可以了

/**
 * @author zmz
 * @since 2021/7/19 20:51
 */
//自动填充处理器用来自动填充处理时间 实现MateObjectHandler类
@Component
@Configuration
@MapperScan("com.ruoyi.project.chouzhou.*.mapper")
public class MybatisPlusConfig implements MetaObjectHandler {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.ORACLE));
        return interceptor;
    }
    

// 插入时的填充策略
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", String.class, DateUtils.getTime());
    }

    // 更新时的填充策略
    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", String.class, DateUtils.getTime());
    }
}

四,修改mybatis的配置(这一步根据实际情况修改)

在mybatis配置中把SqlSessionFactoryBean替换为MybatisSqlSessionFactoryBean

下面是本项目的mybatis配置

/**
 * Mybatis支持*匹配扫描包
 * 
 * @author ruoyi
 */
@Configuration
public class MyBatisConfig
{
    @Autowired
    private Environment env;

    static final String DEFAULT_RESOURCE_PATTERN = "**/*.class";

    public static String setTypeAliasesPackage(String typeAliasesPackage)
    {
        ResourcePatternResolver resolver = (ResourcePatternResolver) new PathMatchingResourcePatternResolver();
        MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver);
        List<String> allResult = new ArrayList<String>();
        try
        {
            for (String aliasesPackage : typeAliasesPackage.split(","))
            {
                List<String> result = new ArrayList<String>();
                aliasesPackage = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                        + ClassUtils.convertClassNameToResourcePath(aliasesPackage.trim()) + "/" + DEFAULT_RESOURCE_PATTERN;
                Resource[] resources = resolver.getResources(aliasesPackage);
                if (resources != null && resources.length > 0)
                {
                    MetadataReader metadataReader = null;
                    for (Resource resource : resources)
                    {
                        if (resource.isReadable())
                        {
                            metadataReader = metadataReaderFactory.getMetadataReader(resource);
                            try
                            {
                                result.add(Class.forName(metadataReader.getClassMetadata().getClassName()).getPackage().getName());
                            }
                            catch (ClassNotFoundException e)
                            {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                if (result.size() > 0)
                {
                    HashSet<String> hashResult = new HashSet<String>(result);
                    allResult.addAll(hashResult);
                }
            }
            if (allResult.size() > 0)
            {
                typeAliasesPackage = String.join(",", (String[]) allResult.toArray(new String[0]));
            }
            else
            {
                throw new RuntimeException("mybatis typeAliasesPackage 路径扫描错误,参数typeAliasesPackage:" + typeAliasesPackage + "未找到任何包");
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return typeAliasesPackage;
    }

    public Resource[] resolveMapperLocations(String[] mapperLocations)
    {
        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
        List<Resource> resources = new ArrayList<Resource>();
        if (mapperLocations != null)
        {
            for (String mapperLocation : mapperLocations)
            {
                try
                {
                    Resource[] mappers = resourceResolver.getResources(mapperLocation);
                    resources.addAll(Arrays.asList(mappers));
                }
                catch (IOException e)
                {
                    // ignore
                }
            }
        }
        return resources.toArray(new Resource[resources.size()]);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception
    {
        String typeAliasesPackage = env.getProperty("mybatis.typeAliasesPackage");
        String mapperLocations = env.getProperty("mybatis.mapperLocations");
        String configLocation = env.getProperty("mybatis.configLocation");
        typeAliasesPackage = setTypeAliasesPackage(typeAliasesPackage);
        VFS.addImplClass(SpringBootVFS.class);

//        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setTypeAliasesPackage(typeAliasesPackage);
  sessionFactory.setMapperLocations(resolveMapperLocations(StringUtils.split(mapperLocations, ",")));
        sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(configLocation));
        return sessionFactory.getObject();
    }
}

好了,结束了,开干吧!

;