All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.antelopeframework.mybatis.shard.ShardContext Maven / Gradle / Ivy

There is a newer version: 1.1.5
Show newest version
package com.github.antelopeframework.mybatis.shard;

import java.util.HashMap;
import java.util.Map;

import com.github.antelopeframework.mybatis.shard.annotation.ShardOn;

import lombok.Getter;

/**
 * 数据源路由选择器上下文环境.
 * 
 * @author yangzhi.yzh
 *
 */
public class ShardContext {
	
	/**
	 * 数据库键.
	 */
	private static final ThreadLocal THREAD_LOCAL_DATASOURCE_KEY;
	
	/**
	 * <数据库表名(原始, 未分别之前), {@link ShardOnPair}>
	 */
	private static final ThreadLocal> THREAD_LOCAL_SHARD_ONS;

	static {
		THREAD_LOCAL_DATASOURCE_KEY = new ThreadLocal<>();
		THREAD_LOCAL_SHARD_ONS = new ThreadLocal<>();
	}
	
	/**
	 * 设置 MyBatis Mapper 方法参数上标注的 {@link ShardOn} 注解及其参数值.
	 * 
	 * @param shardOns
	 */
	public static void setShardOns(Map shardOns) {
		Map _shardOns = THREAD_LOCAL_SHARD_ONS.get();
		if (_shardOns == null) {
			_shardOns = new HashMap<>();
			THREAD_LOCAL_SHARD_ONS.set(_shardOns);
		} else {
			_shardOns.clear();
		}
		
		_shardOns.putAll(shardOns);
	}
	
	/**
	 * 获取当前 MyBatis Mapper 方法参数上标注的 {@link ShardOn} 及其参数值.
	 *  
	 * @return
	 */
	public static Map getShardOns() {
		return THREAD_LOCAL_SHARD_ONS.get();
	} 

	/**
	 * 设置数据库.
	 * 
	 * @param key
	 */
	public static void setDataSourceKey(String key) {
		THREAD_LOCAL_DATASOURCE_KEY.set(key);
	}
	
	/**
	 * 获取数据库.
	 * 
	 * @return
	 */
	public static String getDataSourceKey() {
		return THREAD_LOCAL_DATASOURCE_KEY.get();
	}
	
	/**
	 * 清除当前线程独立的变量.
	 */
	public static void clear() {
		THREAD_LOCAL_DATASOURCE_KEY.remove();
		THREAD_LOCAL_SHARD_ONS.remove();
	}
	
	@Getter
	public static class ShardOnPair {
		/**
		 * {@link ShardOn}
		 */
		private final ShardOn shardOn;
		
		/**
		 * {@link ShardOn} 注解参数对应的值.
		 */
		private final Object shardValue;
		
		/**
		 * 构造函数.
		 * 
		 * @param shardOn
		 * @param shardValue
		 */
		public ShardOnPair(ShardOn shardOn, Object shardValue) {
			this.shardOn = shardOn;
			this.shardValue = shardValue;
		}
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy