springboot integrates mybatisplus in detail

SpringBoot integrates mybatisPlus in detail

Helpless, it is a small new project that only mybatis is not used to, so let’s add plus~

1. Introduce mybatis_plus dependency

     <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>

One thing to note above is that the paging of mybatis_plus will conflict with the paging of pageHelper, because their underlying layers are actually similar. I personally prefer the paging of mybatis_plus, because the joint table paging of pageHelper will be more troublesome, and the joint table paging of mybatis_plus only needs to add the @Select annotation on the mapper layer to write the joint table query statement. But there is no way for the minority to obey the majority, so pageHelper is used for paging.

One thing to note above is that after the dependency of mybatis_plus is introduced, the dependency of mybatis is no longer needed and can be eliminated.

2. Modify the yml configuration of mybatis_plus

First, take a look at the approximate package level of the entire project, mainly to map the mapper and xml files.

# 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

3. Add other configurations of mybatis_plus and package scanning

One of the following two configurations is for paging (of course, in fact, the paging of plus is currently useless due to conflicts with pageHelper, so I discarded it with tears), and the other is for filling and updating basic fields.

The important thing is to add a package scan that corresponds to the package path of your mapper layer.

The deletion of ps:plus is a logical deletion. You only need to annotate @TableLogic on the corresponding deletion identification field. When querying, you can filter based on the changed field.

/**
 * @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());
    }
}

Fourth, modify the configuration of mybatis (this step is modified according to the actual situation)

Replace SqlSessionFactoryBean with MybatisSqlSessionFactoryBean in mybatis configuration

The following is the mybatis configuration of this project

/**
 * 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();
    }
}

Okay, it’s over, let’s get started!

Guess you like

Origin blog.csdn.net/qq_45925197/article/details/131490773