關(guān)于MyBatis中Mapper?XML熱加載優(yōu)化
前幾天在琢磨mybatis xml熱加載的問(wèn)題,原理還是通過(guò)定時(shí)掃描xml文件去跟新,但放到項(xiàng)目上就各種問(wèn)題,由于用了mybatisplus死活不生效。本著"即插即用"的原則,狠心把其中的代碼優(yōu)化了一遍,能夠兼容mybatisplus,還加入了一些日志,直接上代碼
package com.bzd.core.mybatis;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.session.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NestedIOException;
import org.springframework.core.io.Resource;
import com.google.common.collect.Sets;
/**
* 刷新MyBatis Mapper XML 線程
* @author ThinkGem
* @version 2016-5-29
*/
public class MapperRefresh implements java.lang.Runnable {
public static Logger log = LoggerFactory.getLogger(MapperRefresh.class);
private static String filename = "mybatis-refresh.properties";
private static Properties prop = new Properties();
private static boolean enabled; // 是否啟用Mapper刷新線程功能
private static boolean refresh; // 刷新啟用后,是否啟動(dòng)了刷新線程
private Set<String> location; // Mapper實(shí)際資源路徑
private Resource[] mapperLocations; // Mapper資源路徑
private Configuration configuration; // MyBatis配置對(duì)象
private Long beforeTime = 0L; // 上一次刷新時(shí)間
private static int delaySeconds; // 延遲刷新秒數(shù)
private static int sleepSeconds; // 休眠時(shí)間
private static String mappingPath; // xml文件夾匹配字符串,需要根據(jù)需要修改
static {
// try {
// prop.load(MapperRefresh.class.getResourceAsStream(filename));
// } catch (Exception e) {
// e.printStackTrace();
// System.out.println("Load mybatis-refresh “"+filename+"” file error.");
// }
URL url = MapperRefresh.class.getClassLoader().getResource(filename);
InputStream is;
try {
is = url.openStream();
if (is == null) {
log.warn("applicationConfig.properties not found.");
} else {
prop.load(is);
}
} catch (IOException e) {
e.printStackTrace();
}
String value = getPropString("enabled");
System.out.println(value);
enabled = "true".equalsIgnoreCase(value);
delaySeconds = getPropInt("delaySeconds");
sleepSeconds = getPropInt("sleepSeconds");
//mappingPath = getPropString("mappingPath");
delaySeconds = delaySeconds == 0 ? 50 : delaySeconds;
sleepSeconds = sleepSeconds == 0 ? 3 : sleepSeconds;
mappingPath = StringUtils.isBlank(mappingPath) ? "mappings" : mappingPath;
log.debug("[enabled] " + enabled);
log.debug("[delaySeconds] " + delaySeconds);
log.debug("[sleepSeconds] " + sleepSeconds);
log.debug("[mappingPath] " + mappingPath);
}
public static boolean isRefresh() {
return refresh;
}
public MapperRefresh(Resource[] mapperLocations, Configuration configuration) {
this.mapperLocations = mapperLocations;
this.configuration = configuration;
}
@Override
public void run() {
beforeTime = System.currentTimeMillis();
log.debug("[location] " + location);
log.debug("[configuration] " + configuration);
if (enabled) {
// 啟動(dòng)刷新線程
final MapperRefresh runnable = this;
new Thread(new java.lang.Runnable() {
@SneakyThrows
@Override
public void run() {
/*if (location == null){
location = Sets.newHashSet();
log.debug("MapperLocation's length:" + mapperLocations.length);
for (Resource mapperLocation : mapperLocations) {
String s = mapperLocation.toString().replaceAll("\\\\", "/");
s = s.substring("file [".length(), s.lastIndexOf(mappingPath) + mappingPath.length());
s = mapperLocation.getFile().getParent();
if (!location.contains(s)) {
location.add(s);
log.debug("Location:" + s);
}
}
log.debug("Locarion's size:" + location.size());
}*/
try {
Thread.sleep(delaySeconds * 1000);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
refresh = true;
System.out.println("========= Enabled refresh mybatis mapper =========");
while (true) {
try {
log.info("start refresh");
List<Resource> res = getModifyResource(mapperLocations,beforeTime);
if(res.size()>0)
runnable.refresh(res);
// 如果刷新了文件,則修改刷新時(shí)間,否則不修改
beforeTime = System.currentTimeMillis();
log.info("end refresh("+res.size()+")");
} catch (Exception e1) {
e1.printStackTrace();
}
try {
Thread.sleep(sleepSeconds * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "MyBatis-Mapper-Refresh").start();
}
}
private List<Resource> getModifyResource(Resource[] mapperLocations,long time){
List<Resource> resources = new ArrayList<>();
for (int i = 0; i < mapperLocations.length; i++) {
try {
if(isModify(mapperLocations[i],time))
resources.add(mapperLocations[i]);
} catch (IOException e) {
throw new RuntimeException("讀取mapper文件異常",e);
}
}
return resources;
}
private boolean isModify(Resource resource,long time) throws IOException {
if (resource.lastModified() > time) {
return true;
}
return false;
}
/**
* 執(zhí)行刷新
* @param filePath 刷新目錄
* @param beforeTime 上次刷新時(shí)間
* @throws NestedIOException 解析異常
* @throws FileNotFoundException 文件未找到
* @author ThinkGem
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
private void refresh(List<Resource> mapperLocations) throws Exception {
// 獲取需要刷新的Mapper文件列表
/*List<File> fileList = this.getRefreshFile(new File(filePath), beforeTime);
if (fileList.size() > 0) {
log.debug("Refresh file: " + fileList.size());
}*/
for (int i = 0; i < mapperLocations.size(); i++) {
Resource resource = mapperLocations.get(i);
InputStream inputStream = resource.getInputStream();
System.out.println("refreshed : "+resource.getDescription());
//這個(gè)是mybatis 加載的資源標(biāo)識(shí),沒(méi)有絕對(duì)標(biāo)準(zhǔn)
String resourcePath = resource.getDescription();
try {
clearMybatis(resourcePath);
//重新編譯加載資源文件。
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(inputStream, configuration,
resourcePath, configuration.getSqlFragments());
xmlMapperBuilder.parse();
} catch (Exception e) {
throw new NestedIOException("Failed to parse mapping resource: '" + resourcePath + "'", e);
} finally {
ErrorContext.instance().reset();
}
// System.out.println("Refresh file: " + mappingPath + StringUtils.substringAfterLast(fileList.get(i).getAbsolutePath(), mappingPath));
/*if (log.isDebugEnabled()) {
log.debug("Refresh file: " + fileList.get(i).getAbsolutePath());
log.debug("Refresh filename: " + fileList.get(i).getName());
}*/
}
}
private void clearMybatis(String resource) throws NoSuchFieldException, IllegalAccessException {
// 清理原有資源,更新為自己的StrictMap方便,增量重新加載
String[] mapFieldNames = new String[]{
"mappedStatements", "caches",
"resultMaps", "parameterMaps",
"keyGenerators", "sqlFragments"
};
for (String fieldName : mapFieldNames){
Field field = configuration.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
Map map = ((Map)field.get(configuration));
if (!(map instanceof StrictMap)){
Map newMap = new StrictMap(StringUtils.capitalize(fieldName) + "collection");
for (Object key : map.keySet()){
try {
newMap.put(key, map.get(key));
}catch(IllegalArgumentException ex){
newMap.put(key, ex.getMessage());
}
}
field.set(configuration, newMap);
}
}
// 清理已加載的資源標(biāo)識(shí),方便讓它重新加載。
Field loadedResourcesField = configuration.getClass().getDeclaredField("loadedResources");
loadedResourcesField.setAccessible(true);
Set loadedResourcesSet = ((Set)loadedResourcesField.get(configuration));
loadedResourcesSet.remove(resource);
}
/**
* 獲取需要刷新的文件列表
* @param dir 目錄
* @param beforeTime 上次刷新時(shí)間
* @return 刷新文件列表
*/
private List<File> getRefreshFile(File dir, Long beforeTime) {
List<File> fileList = new ArrayList<File>();
File[] files = dir.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isDirectory()) {
fileList.addAll(this.getRefreshFile(file, beforeTime));
} else if (file.isFile()) {
if (this.checkFile(file, beforeTime)) {
fileList.add(file);
}
} else {
System.out.println("Error file." + file.getName());
}
}
}
return fileList;
}
/**
* 判斷文件是否需要刷新
* @param file 文件
* @param beforeTime 上次刷新時(shí)間
* @return 需要刷新返回true,否則返回false
*/
private boolean checkFile(File file, Long beforeTime) {
if (file.lastModified() > beforeTime) {
return true;
}
return false;
}
/**
* 獲取整數(shù)屬性
* @param key
* @return
*/
private static int getPropInt(String key) {
int i = 0;
try {
i = Integer.parseInt(getPropString(key));
} catch (Exception e) {
}
return i;
}
/**
* 獲取字符串屬性
* @param key
* @return
*/
private static String getPropString(String key) {
return prop == null ? null : prop.getProperty(key).trim();
}
/**
* 重寫(xiě) org.apache.ibatis.session.Configuration.StrictMap 類(lèi)
* 來(lái)自 MyBatis3.4.0版本,修改 put 方法,允許反復(fù) put更新。
*/
public static class StrictMap<V> extends HashMap<String, V> {
private static final long serialVersionUID = -4950446264854982944L;
private String name;
public StrictMap(String name, int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
this.name = name;
}
public StrictMap(String name, int initialCapacity) {
super(initialCapacity);
this.name = name;
}
public StrictMap(String name) {
super();
this.name = name;
}
public StrictMap(String name, Map<String, ? extends V> m) {
super(m);
this.name = name;
}
@SuppressWarnings("unchecked")
public V put(String key, V value) {
// ThinkGem 如果現(xiàn)在狀態(tài)為刷新,則刷新(先刪除后添加)
if (MapperRefresh.isRefresh()) {
remove(key);
// MapperRefresh.log.debug("refresh key:" + key.substring(key.lastIndexOf(".") + 1));
}
// ThinkGem end
if (containsKey(key)) {
throw new IllegalArgumentException(name + " already contains value for " + key);
}
if (key.contains(".")) {
final String shortKey = getShortName(key);
if (super.get(shortKey) == null) {
super.put(shortKey, value);
} else {
super.put(shortKey, (V) new Ambiguity(shortKey));
}
}
return super.put(key, value);
}
public V get(Object key) {
V value = super.get(key);
if (value == null) {
throw new IllegalArgumentException(name + " does not contain value for " + key);
}
if (value instanceof Ambiguity) {
throw new IllegalArgumentException(((Ambiguity) value).getSubject() + " is ambiguous in " + name
+ " (try using the full name including the namespace, or rename one of the entries)");
}
return value;
}
private String getShortName(String key) {
final String[] keyparts = key.split("\\.");
return keyparts[keyparts.length - 1];
}
protected static class Ambiguity {
private String subject;
public Ambiguity(String subject) {
this.subject = subject;
}
public String getSubject() {
return subject;
}
}
}
}
這里提供兩種配置方式一種是springboot,一種就是普通的spring項(xiàng)目
1.springboot 方式 就是
package com.bzd.bootadmin.conf;
import com.bzd.core.mybatis.MapperRefresh;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import javax.annotation.PostConstruct;
/**
*
* @author Created by bzd on 2020/12/28/15:10
**/
@Configuration
@MapperScan(value = {"com.bzd.bootadmin.modular.index.mapper"})
public class MybatisConfig {
@Autowired
SqlSessionFactory factory;
@Autowired
MybatisProperties properties;
@PostConstruct
public void postConstruct() {
Resource[] resources = this.properties.resolveMapperLocations();
new MapperRefresh(resources, factory.getConfiguration()).run();
}
}
2:普通spring項(xiàng)目
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.core.io.Resource;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Created By lxr on 2020/5/3
**/
public class RefreshStarter {
SqlSessionFactory factory;
Resource[] mapperLocations;
@PostConstruct
public void postConstruct() throws IOException {
Resource[] resources = mapperLocations;
enableMybatisPlusRefresh(factory.getConfiguration());
new MapperRefresh(resources, factory.getConfiguration()).run();
}
/**
* 反射配置開(kāi)啟 MybatisPlus 的 refresh,不使用MybatisPlus也不會(huì)有影響
* @param configuration
*/
public void enableMybatisPlusRefresh(Configuration configuration){
try {
Method method = Class.forName("com.baomidou.mybatisplus.toolkit.GlobalConfigUtils")
.getMethod("getGlobalConfig", Configuration.class);
Object globalConfiguration = method.invoke(null, configuration);
method = Class.forName("com.baomidou.mybatisplus.entity.GlobalConfiguration")
.getMethod("setRefresh", boolean.class);
method.invoke(globalConfiguration, true);
} catch (ClassNotFoundException e) {
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
public SqlSessionFactory getFactory() {
return factory;
}
public void setFactory(SqlSessionFactory factory) {
this.factory = factory;
}
public Resource[] getMapperLocations() {
return mapperLocations;
}
public void setMapperLocations(Resource[] mapperLocations) {
this.mapperLocations = mapperLocations;
}
}
在xml中配置
<bean class="com.foxtail.core.mybatis.RefreshStarter"> <property name="mapperLocations"> <array> <value>classpath:com/foxtail/mapping/*/*.xml</value> <value>classpath:com/foxtail/mapping/*.xml</value> </array> </property> <property name="factory" ref="sqlSessionFactory" /> </bean>
最后在resources中加入mybatis-refresh.properties
#是否開(kāi)啟刷新線程 enabled=true #延遲啟動(dòng)刷新程序的秒數(shù) delaySeconds=5 #刷新掃描間隔的時(shí)長(zhǎng)秒數(shù) sleepSeconds=3
到這里就大功告成了,最后加到代碼里面有沒(méi)有生效呢,改完sql之后總會(huì)想到底是更新了還是沒(méi)更新,又看不到,這是程序員最頭疼的。因?yàn)榧恿巳罩径疾挥脫?dān)心啦

到此這篇關(guān)于關(guān)于MyBatis中Mapper XML熱加載優(yōu)化的文章就介紹到這了,更多相關(guān)MyBatis Mapper XML熱加載內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- MyBatis源碼剖析之Mapper代理方式詳解
- mybatis配置mapper-locations的坑及解決
- mybatis中mapper-locations的作用
- Mybatis的mapper.xml中if標(biāo)簽test判斷的用法說(shuō)明
- MyBatis實(shí)現(xiàn)注冊(cè)及獲取Mapper
- mybatis中的mapper.xml使用循環(huán)語(yǔ)句
- Mybatis中mapper.xml實(shí)現(xiàn)熱加載介紹
- mybatis?mapper.xml中如何根據(jù)數(shù)據(jù)庫(kù)類(lèi)型選擇對(duì)應(yīng)SQL語(yǔ)句
- MyBatis映射器mapper快速入門(mén)教程
相關(guān)文章
Java技巧函數(shù)方法實(shí)現(xiàn)二維數(shù)組遍歷
這篇文章主要介紹了Java技巧函數(shù)方法實(shí)現(xiàn)二維數(shù)組遍歷,二維數(shù)組遍歷,每個(gè)元素判斷下是否為偶數(shù),相關(guān)內(nèi)容需要的小伙伴可以參考一下2022-08-08
java中double強(qiáng)制轉(zhuǎn)換int引發(fā)的OOM問(wèn)題記錄
這篇文章主要介紹了java中double強(qiáng)制轉(zhuǎn)換int引發(fā)的OOM問(wèn)題記錄,本文給大家分享問(wèn)題排查過(guò)程,感興趣的朋友跟隨小編一起看看吧2024-10-10
SpringBoot實(shí)現(xiàn)物品點(diǎn)贊功能
這篇文章主要介紹了SpringBoot物品點(diǎn)贊功能實(shí)現(xiàn),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04
Springboot項(xiàng)目中如何讓非Spring管理的類(lèi)獲得一個(gè)注入的Bean
這篇文章主要介紹了Springboot項(xiàng)目中如何讓非Spring管理的類(lèi)獲得一個(gè)注入的Bean問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12
SpringBoot整合阿里云OSS對(duì)象存儲(chǔ)服務(wù)的實(shí)現(xiàn)
這篇文章主要介紹了SpringBoot整合阿里云OSS對(duì)象存儲(chǔ)服務(wù)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08
Spring Boot學(xué)習(xí)入門(mén)之統(tǒng)一異常處理詳解
我們?cè)谧鯳eb應(yīng)用的時(shí)候,請(qǐng)求處理過(guò)程中發(fā)生錯(cuò)誤是非常常見(jiàn)的情況。下面這篇文章主要給大家介紹了關(guān)于Spring Boot學(xué)習(xí)入門(mén)之統(tǒng)一異常處理的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下。2017-09-09
修改SpringBoot 中MyBatis的mapper.xml文件位置的過(guò)程詳解
由于MyBatis默認(rèn)的mapper.xml的掃描位置是resource文件下,但是不可能整個(gè)項(xiàng)目的mapper.xml文件都放在resource下,如果文件較少還行,但是如果文件比較多,太麻煩了,所以本文給大家介紹了修改SpringBoot 中MyBatis的mapper.xml文件位置的過(guò)程,需要的朋友可以參考下2024-08-08
IDEA創(chuàng)建javaee項(xiàng)目依賴(lài)war exploded變紅失效的解決方案
在使用IntelliJ IDEA創(chuàng)建JavaEE項(xiàng)目時(shí),可能會(huì)遇到Tomcat部署的warexploded文件出現(xiàn)問(wèn)題,解決方法是首先刪除有問(wèn)題的warexploded依賴(lài),然后根據(jù)圖示重新導(dǎo)入項(xiàng)目,此外,調(diào)整虛擬路徑有時(shí)也能有效解決問(wèn)題2024-09-09

