SpringBoot Mybatis 自动加载XML或 手动加载

实现启动项目自动加载 XML 

import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author LMinY
 * @description: 开启自动刷新XML
 * @date 2020/8/27
 */
@Configuration
public class XMLMapperConfing {
    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    /**
     * 根据配置文件的值 是否开启实时刷新
     */
    @Value("${XMLMapperRefresh}")
    Boolean XMLMapperRefresh;

    @Bean
    public void  xMLMapperLoader() {
        if(XMLMapperRefresh) {
            new XMLMapperLoader(sqlSessionFactory,"/mapper");
        }
    }
}

实现手动加载XML 如果只需要执行一次可以将监听线程重写或者删除XMLMapperLoader ().startThreadListener()

 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author LMinY
 * @description: 测试
 * @date 2020/8/27
 */
@RestController
public class testController {
    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    /**
     * 第二种方式 通过URL来刷新
     * @return
     */
    @RequestMapping("refersh")
    public String refershMyBatisXml() {
        return new XMLMapperLoader(sqlSessionFactory,"/mapper").readMapperXml();
    }

}

1.1 此类主要将项目启动时xml文件加载到 sqlSessionFactory 中的 Configuration缓存清除,再扫描本地xml加入到该缓存中,从而达到,xml没有经过编译也可以实现实时更新(网上也有其他的加载的编译后的xml,也就是build路径加的xml,但如果项目没有编译,xml无法实时更新,注意scanMapperXml()方法的路径你要换成自己对应的XML文件路径

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.lang.reflect.Field;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
public class XMLMapperLoader {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private SqlSessionFactory sqlSessionFactory;
    private Resource[] mapperLocations;
    private String packageSearchPath = "/mapper";

    public XMLMapperLoader(SqlSessionFactory sqlSessionFactory, String packageSearchPath) {
        this.sqlSessionFactory = sqlSessionFactory;
        if (packageSearchPath != null && packageSearchPath != "") {
            this.packageSearchPath = packageSearchPath;
        }
        startThreadListener();
    }

    public void startThreadListener() {
        ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
        //每10秒执行一次
        service.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                readMapperXml();
            }
        }, 0, 10, TimeUnit.SECONDS);
        readMapperXml();
    }

    public String readMapperXml() {
        try {
            org.apache.ibatis.session.Configuration configuration = sqlSessionFactory.getConfiguration();
            // 扫描文件
            this.scanMapperXml();

            if (true) {
                // 清空configuration map的数据
                this.removeConfig(configuration);

                // 将xml 重新加载
                for (Resource configLocation : mapperLocations) {
                    if ("TestMapper.xml".equals(configLocation.getFilename())) {

                        try {
                            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configLocation.getInputStream(), configuration, configLocation.toString(), configuration.getSqlFragments());
                            xmlMapperBuilder.parse();
                            logger.debug("mapper文件[" + configLocation.getFilename() + "]缓存加载成功");
                        } catch (IOException e) {
                            logger.debug("mapper文件[" + configLocation.getFilename() + "]不存在或内容格式不对");
                            continue;
                        }
                    }
                }
            }

            return "refresh mybatis xml succssful ";
        } catch (Exception e) {
            e.printStackTrace();
            return "refresh mybatis xml fail";
        }
    }


    /**
     * 扫描xml文件所在的路径
     *
     * @throws IOException
     */
    private void scanMapperXml()  {
        //根据自己项目的实际路径查替换,最终是找到非编译的 xml所在的文件夹路径
        String fileUrl =this.getClass().getResource(packageSearchPath)
                .getPath().replace("/main","")
                .replace("build","src/main");
        File file = new File(fileUrl);
        File[] matchingFiles = file.listFiles();
        Set<Resource> result = new LinkedHashSet<>(matchingFiles.length);
        for (File files : matchingFiles) {
            result.add(new FileSystemResource(files));
        }
        this.mapperLocations = result.toArray(new Resource[0]);
    }

    /**
     * 清空Configuration中几个重要的缓存
     * @param configuration
     * @throws Exception
     */
    private void removeConfig(Configuration configuration) throws Exception {
        Class<?> classConfig = configuration.getClass();
        clearMap(classConfig, configuration, "mappedStatements");
        clearMap(classConfig, configuration, "caches");
        clearMap(classConfig, configuration, "resultMaps");
        clearMap(classConfig, configuration, "parameterMaps");
        clearMap(classConfig, configuration, "keyGenerators");
        clearMap(classConfig, configuration, "sqlFragments");
        clearSet(classConfig, configuration, "loadedResources");

    }

    private void clearMap(Class<?> classConfig, Configuration configuration, String fieldName) throws Exception {
        Field field = null;

        if (configuration.getClass().getName().equals("com.baomidou.mybatisplus.core.MybatisConfiguration")) {
            field = classConfig.getSuperclass().getDeclaredField(fieldName);
        } else {
            field = classConfig.getClass().getDeclaredField(fieldName);
        }
        field.setAccessible(true);
        Map mapConfig = (Map) field.get(configuration);
        mapConfig.clear();
    }


    private void clearSet(Class<?> classConfig, Configuration configuration, String fieldName) throws Exception {
        Field field = null;
        if (configuration.getClass().getName().equals("com.baomidou.mybatisplus.core.MybatisConfiguration")) {
            field = classConfig.getSuperclass().getDeclaredField(fieldName);
        } else {
            field = classConfig.getClass().getDeclaredField(fieldName);
        }
        field.setAccessible(true);
        Set setConfig = (Set) field.get(configuration);
        setConfig.clear();
    }


}

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Spring Boot和MyBatis自动生成数据库表的步骤: 1.在pom.xml文件中添加MyBatisMyBatis Generator的依赖: ```xml <dependencies> <!-- MyBatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <!-- MyBatis Generator --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.4.0</version> </dependency> </dependencies> ``` 2.在application.properties文件中配置数据库连接信息: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8 spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver ``` 3.创建实体类和Mapper接口,使用注解或XML文件配置SQL语句。 4.在resources目录下创建generatorConfig.xml文件,配置MyBatis Generator的相关信息,例如数据库连接信息、生成的实体类和Mapper接口的包名、生成的表名等。 ```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <context id="DB2Tables" targetRuntime="MyBatis3"> <jdbcConnection driverClass="${jdbc.driverClass}" connectionURL="${jdbc.connectionURL}" userId="${jdbc.userId}" password="${jdbc.password}"> </jdbcConnection> <javaModelGenerator targetPackage="com.example.demo.entity" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.demo.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <table tableName="user"></table> </context> </generatorConfiguration> ``` 5.在Maven的命令行中执行以下命令,生成实体类和Mapper接口: ```shell mvn mybatis-generator:generate ``` 6.查看生成的实体类和Mapper接口,如果有需要可以进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值