开发喵星球

若依使用mybatisPlus进行代码生成(200)

🎉🎉若依系列持续更新第200篇🎉🎉

特此给大家推荐一个AI工具,嘎嘎好用,前10名留言送月卡哦!

集成了ChatGPT4.0、claude3、gemini…

写代码、改bug超级方便,本文也感谢开发喵AI的支持🥳

1 添加依赖

项目根目录下的pom.xml文件中

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.1</version>
</dependency>

ruoyi-common模块的pom.xml文件中

<dependencies>
    <!--   mybatis-plus     -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
    </dependency>
</dependencies>

2 修改mybatisconfig

修改ruoyi-framework模块config文件下的mybatisconfig

/**
 * Mybatis支持*匹配扫描包
 *
 * @author 
 */
@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();
//        sessionFactory.setDataSource(dataSource);
//        sessionFactory.setTypeAliasesPackage(typeAliasesPackage);
//        sessionFactory.setMapperLocations(resolveMapperLocations(StringUtils.split(mapperLocations, ",")));
//        sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(configLocation));
//        return sessionFactory.getObject();
//    }
}

3 修改application.yml

位置:ruoyi-admin模块的application.yml文件
注释掉mybatis配置

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

#mybatis-plus
mybatis-plus:
  # 对应的 XML 文件位置
  mapperLocations: classpath*:mapper/**/*Mapper.xml
  # 实体扫描,多个package用逗号或者分号分隔
  typeAliasesPackage: com.ruoyi.**.domain
  # 加载全局的配置文件
  configLocation: classpath:mybatis/mybatis-config.xml

  type-aliases-package: com.ruoyi.**.domain
  mapper-locations: classpath*:mapper/**/*Mapper.xml
  configuration:
    cache-enabled: true
    use-generated-keys: true
    default-executor-type: simple
    log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl

4 修改代码生成器

4.1 domain.java.vm

import com.baomidou.mybatisplus.annotation.TableName;
@TableName("${tableName}")

4.2 mapper.java.vm

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface {ClassName}Mapper extends BaseMapper<{ClassName}>

4.3 service.java.vm

import com.baomidou.mybatisplus.extension.service.IService;
public interface I{ClassName}Service extends IService<{ClassName}>

4.4 serviceImpl.java.vm

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
public class {ClassName}ServiceImpl extends ServiceImpl<{ClassName}Mapper,{ClassName}> implements I{ClassName}Service

4.5 generator.yml,自动去除表前缀改为true。

tablePrefix表前缀,生成类名时省略表前缀。这里前缀有sys_
packageName表示生成代码的路径,这里默认是com.ruoyi.system

5 MybatisPlus分页插件初始化配置

位置:在ruoyi-framework模块下新增MybatisPlusConfig.java

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan("com.*.*.mapper") //指定扫描目录
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); //注意使用哪种数据库
        return interceptor;
    }
}

6 修改sysconfig

6.1 SysConfig.java

位置:ruoyi-system/src/main/java/com/ruoyi/system/domain/SysConfig.java

import com.baomidou.mybatisplus.annotation.TableName;

@TableName("sys_config")

6.2 SysConfigMapper.java

位置:ruoyi-system/src/main/java/com/ruoyi/system/mapper/SysConfigMapper.java

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

public interface SysConfigMapper extends BaseMapper<SysConfig>

6.3 ISysConfigService.java

ruoyi-system/src/main/java/com/ruoyi/system/service/ISysConfigService.java

import com.baomidou.mybatisplus.extension.service.IService;

public interface ISysConfigService extends IService<SysConfig>

6.4 SysConfigServiceImpl.java

位置:ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysConfigServiceImpl.java

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements ISysConfigService

至此,若依使用mybatisPlus进行代码生成已完成。

   
分类:Java/OOP 作者:无限繁荣, 吴蓉 发表于:2024-05-06 21:17:58 阅读量:104
<<   >>


powered by kaifamiao