首页 > 数据库 >读取配置连接信息,利用mybatis进行数据库连接操作

读取配置连接信息,利用mybatis进行数据库连接操作

时间:2024-08-15 15:25:06浏览次数:10  
标签:dataSourceKey String dds sqlTemplateMap public static mybatis 连接 读取

mybatisConnConfig.properties配置文件内容
default.configpath=config/mybatis/mybatis-config.xml

dw.jdbc.system.driver=com.mysql.jdbc.Driver
dw.jdbc.system.url=
dw.jdbc.system.username=
dw.jdbc.system.password=

ralid.jdbc.system.driver=com.mysql.jdbc.Driver
ralid.jdbc.system.url=
ralid.jdbc.system.username=
ralid.jdbc.system.password=
MybatisConnUtils连接封装工具类
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

@Component
public class MybatisConnUtils{

	private static final Log logger = LogFactory.getLog(MybatisConnUtils.class.getName());

	public final static String MyBATIS_PROPERTITY_PATH = "config/mybatis/mybatisConnConfig.properties";

	public final static String DRIVER = "jdbc.system.driver";

	public final static String USERNAME = "jdbc.system.username";

	public final static String PASSWORD = "jdbc.system.password";

	public final static String URL = "jdbc.system.url";

	public final static String CONFIGPATH = "default.configpath";

	private static Properties properties;

	private static Map<String, List<String>> mapMapperXmlLocations;

	public void setMapMapperXmlLocations(Map<String, List<String>> mapMapperXmlLocations) {
		MybatisConnUtils.mapMapperXmlLocations = mapMapperXmlLocations;
	}

	private static Map<String, SqlSessionTemplate> sqlTemplateMap = new HashMap<String, SqlSessionTemplate>();

	public static void removeConnectFromMap(String dataSourceKey) {
		if(sqlTemplateMap.containsKey(dataSourceKey)){
			sqlTemplateMap.remove(dataSourceKey);
		}
	}

	public static void closeConnection() {
		for (SqlSessionTemplate sqlSessionTemplate : sqlTemplateMap.values()) {
			sqlSessionTemplate.close();
		}
	}

	static {
		if (properties == null) {
			synchronized (logger) {
				if (properties == null) {
					properties = new Properties();
					try {
						properties.load(MybatisConnUtils.class.getClassLoader()
								.getResourceAsStream(MyBATIS_PROPERTITY_PATH));

					} catch (IOException e) {
						logger.error("Load config/mybatis/mybatisConnConfig error", e);
					}
				}
			}
		}
	}

	public static void initSqlTemplateMap() {
		Set<String> dataSourceKeySet = new HashSet<String>();
		for (Object key : properties.keySet()) {
			String keyStr = key.toString();
			if (StringUtils.isNotEmpty(keyStr)) {
				String dataSourceKey = keyStr.split("\\.")[0];
				dataSourceKeySet.add(dataSourceKey);
			}
		}
		Iterator<String> iterator = dataSourceKeySet.iterator();
		while (iterator.hasNext()) {
			String key = iterator.next();
			initDataSourceByProp(key);
		}
	}

	public static void initDataSourceByProp(String dataSourceKey) {
		String dataSourceKeyDot = dataSourceKey + ".";
		if (!sqlTemplateMap.containsKey(dataSourceKey) && !"default".equals(dataSourceKey)) {
			DruidDataSource dds = new DruidDataSource();
			String driverClassName = properties.getProperty(dataSourceKeyDot + DRIVER);
			String url = properties.getProperty(dataSourceKeyDot + URL);
			String username = properties.getProperty(dataSourceKeyDot + USERNAME);
			String password = properties.getProperty(dataSourceKeyDot + PASSWORD);
			String configLocation = properties.getProperty(CONFIGPATH);
			int initialSize = 10;
			int maxActive = 150;
			if ("spc".equals(dataSourceKey)) {
				initialSize = 5;
				maxActive = 20;
			}
			int minIdle = 10;
			int maxWait = 60000;
			boolean poolPreparedStatements = true;
			int maxOpenPreparedStatements = 100;
			String validationQuery = "select * from dual";
			if ("com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(driverClassName)
					|| "com.mysql.jdbc.Driver".equals(driverClassName))
				validationQuery = "select 1";
			else if ("com.ibm.db2.jcc.DB2Driver".equals(driverClassName))
				validationQuery = "select 1 from sysibm.sysdummy1";
			boolean testOnBorrow = false;
			boolean testOnReturn = false;
			boolean testWhileIdle = true;
			int timeBetweenEvictionRunsMillis = 60000;
			dds.setDriverClassName(driverClassName);
			dds.setUrl(url);
			dds.setUsername(username);
			dds.setPassword(password);
			dds.setInitialSize(initialSize);
			dds.setMaxActive(maxActive);
			dds.setMinIdle(minIdle);
			dds.setMaxWait(maxWait);
			dds.setPoolPreparedStatements(poolPreparedStatements);
			dds.setMaxOpenPreparedStatements(maxOpenPreparedStatements);
			dds.setValidationQuery(validationQuery);
			dds.setTestOnBorrow(testOnBorrow);
			dds.setTestOnReturn(testOnReturn);
			dds.setTestWhileIdle(testWhileIdle);
			dds.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
			SqlSessionFactoryBean sqlSF = new SqlSessionFactoryBean();
			sqlSF.setDataSource(dds);
			// 注入xml
			initXml(dataSourceKey, sqlSF);
			//
			Resource res = new ClassPathResource(configLocation);
			sqlSF.setConfigLocation(res);
			try {
				SqlSessionTemplate sqlTemplate = new SqlSessionTemplate(sqlSF.getObject());
				sqlTemplateMap.put(dataSourceKey, sqlTemplate);
			} catch (Exception e) {
				logger.error("mybatis init error ", e);
			}
		}

	}

	public static List<Object> getList(String dataSourceKey, String nameSpace, String selectId, Object parameter) {
		if (sqlTemplateMap.get(dataSourceKey) == null) {
			initDataSourceByProp(dataSourceKey);
		}
		SqlSessionTemplate sqlSessionTemplate = sqlTemplateMap.get(dataSourceKey);
		List<Object> list = sqlSessionTemplate.selectList(nameSpace + "." + selectId, parameter);
		return list;
	}

	public static <T> List<T> getList(String dataSourceKey, T t, String nameSpace, String selectId, Object parameter) {
		if (sqlTemplateMap.get(dataSourceKey) == null) {
			initDataSourceByProp(dataSourceKey);
		}
		SqlSessionTemplate sqlSessionTemplate = sqlTemplateMap.get(dataSourceKey);
		List<T> list = sqlSessionTemplate.selectList(nameSpace + "." + selectId, parameter);
		return list;
	}

	public static <T> T getOne(String dataSourceKey, String nameSpace, String selectId, Object parameter){
		if (sqlTemplateMap.get(dataSourceKey) == null) {
			initDataSourceByProp(dataSourceKey);
		}
		SqlSessionTemplate sqlSessionTemplate = sqlTemplateMap.get(dataSourceKey);
		T tValue = sqlSessionTemplate.selectOne(nameSpace + "." + selectId, parameter);
		return tValue;
	}

	public static int insert(String dataSourceKey, String nameSpaceAndSqlId, Object parameter) {
		if (sqlTemplateMap.get(dataSourceKey) == null) {
			initDataSourceByProp(dataSourceKey);
		}
		SqlSessionTemplate sqlSessionTemplate = sqlTemplateMap.get(dataSourceKey);
		int num = sqlSessionTemplate.insert(nameSpaceAndSqlId, parameter);
		return num;
	}

	public static int delete(String dataSourceKey, String nameSpaceAndSqlId, Object parameter) {
		if (sqlTemplateMap.get(dataSourceKey) == null) {
			initDataSourceByProp(dataSourceKey);
		}
		SqlSessionTemplate sqlSessionTemplate = sqlTemplateMap.get(dataSourceKey);
		int num = sqlSessionTemplate.delete(nameSpaceAndSqlId, parameter);

		return num;
	}

	public static int update(String dataSourceKey, String nameSpaceAndSqlId, Object parameter) {
		if (sqlTemplateMap.get(dataSourceKey) == null) {
			initDataSourceByProp(dataSourceKey);
		}
		SqlSessionTemplate sqlSessionTemplate = sqlTemplateMap.get(dataSourceKey);
		int num = sqlSessionTemplate.update(nameSpaceAndSqlId, parameter);
		return num;
	}

	public static void main(String[] args) {
		
	}

	public static void initXml(String dataSourceKey, SqlSessionFactoryBean sqlSessionFactory) {
		if (mapMapperXmlLocations == null)
			return;
		List<Resource> resAllList = new ArrayList<Resource>();
		List<String> mapperXmlLocations = mapMapperXmlLocations.get(dataSourceKey);
		// spc测试
		/*
		 * List<String> mapperXmlLocations=new ArrayList<String>();
		 * mapperXmlLocations.add(
		 * "classpath:/com/dao/impl/spc/mybatis/SPCHistorySPCSouce.xml")
		 * ;
		 */
		if (mapperXmlLocations != null) {
			for (String mapperXmlLocation : mapperXmlLocations) {
				ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
				Resource[] resources;
				try {
					resources = resourcePatternResolver.getResources(mapperXmlLocation);
					List<Resource> resList = Arrays.asList(resources);
					resAllList.addAll(resList);
					// sqlSessionFactory.setMapperLocations(resources);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			Resource[] resSources = new Resource[resAllList.size()];
			resAllList.toArray(resSources);
			sqlSessionFactory.setMapperLocations(resSources);
		}
	}

}
MybatisDataSourceKey常量对象
public interface MybatisDataSourceKey {

    String RALID = "ralid";

    String DW = "dw";
}

调用示例

List<ZsPlanExecutionDto> dtos = MybatisConnUtils.getList(MybatisDataSourceKey.DW, new ZsPlanExecutionDto(),"com.dao.impl.produceManagement.SbPlanExecutionMapper", "queryZsExecution", queryDate);

标签:dataSourceKey,String,dds,sqlTemplateMap,public,static,mybatis,连接,读取
From: https://blog.csdn.net/weixin_64332654/article/details/141123269

相关文章

  • SpringBoot整合MyBatis,入门教程,细节无敌,不能错过
    需求SpringBoot整合MyBatis。实现步骤搭建SpringBoot工程引入mybatis起步依赖、添加mysql驱动编写DataSource和MyBatis相关配置定义表和实体类编写dao和mapper文件/纯注解开发测试惨痛的教训同一个项目里,application.*文件只能有一个,如果有多个就会出现一些神奇问题......
  • Uefi ABL读取XBL设置的标志位
    PBL(启动固化程序)->XBL(扩展引导加载程序,负责初始化芯片驱动和核心应用功能。XBL通常会加载一些平台相关的驱动程序,并提供通用接口)->ABL(应用引导加载程序,负责引导操作系统的启动。)高通启用UEFI架构的bootloader,有些时候有些状态值,需要ABL阶段获取.上层思维总是以属性来开端,实......
  • Qt5编译qmqtt库使用MQTT协议连接华为云IOT完成数据上传与交互
    一、前言随着物联网技术的发展,越来越多的设备通过网络互相连接,形成了庞大的智能系统。这些系统能够收集、分析并响应各种数据,从而实现自动化控制和智能化管理。在这个背景下,MQTT成为了一个广泛使用的轻量级消息传输协议,特别适用于资源受限的环境,如移动应用或远程传感器网......
  • java使用动态链接库读取Fanuc设备,在linux环境部署时报错:FOCAS2 log file is not found
    在linux环境中,使用java调用动态链接库的方式读取Fanuc,报错“FOCAS2logfileisnotfound”解决办法linux环境使用cnc_allclibhndl3之前,需要先使用cnc_startupprocess启用并指定日志文件,否则会报错:"FOCAS2logfileisnotfound"。会包含cnc_startupprocess,windows的dll库......
  • Mybatis如何动态生成插入的列及批量插入值
    有时会遇到根据特定的情况动态创建表,并对表进行批量插入,对于Mybatis来说,也是非常简单的。先看dao层voidinsertBatch(@Param("tableName")StringtableName,@Param("dbColumns")List<String>dbColumns,@Param("dbValues")List<LinkedHashMap>dbValues);注:这里的值d......
  • Mybatis学习日记-day4-ResultMap
    一、学习目标    在之前的学习博客里对数据进行增删改查的操作,都是基于数据库表的列名Java对象的属性名一致的情况下,但是,这个世界并不是这么美好。        当数据库表的列名与Java对象的属性名不一致,或者数据类型需要特殊处理;此外,如果数据库中的某个列是枚......
  • 住宅代理IP连接不上?解决排查方法集合
    住宅代理在现代互联网使用中起着至关重要的作用,它们用于各种目的,从在线隐私保护到数据收集,再到跨地理位置访问。然而,在配置到手机/电脑等设备时你可能会遇到住宅代理不起作用的情况。这可能是由多种因素造成的,所以让我们来看看可能的原因以及如何处理它们。一、住宅代理不可......
  • TikTok网络无法连接?4个方法解决它
    “Nonetworkconnection”!当你信心满满下载并准备开始运营TikTok时,屏幕上如果提示“无互联网连接”非常难办。有很多因素可能会导致此问题,包括网络连接无效、应用程序故障等。接下来将为你盘点主要的原因与解决方法。一、无网络连接的原因1、地区网络限制TikTok作为海外版......
  • 住宅代理IP连接不上?解决排查方法集合
    住宅代理在现代互联网使用中起着至关重要的作用,它们用于各种目的,从在线隐私保护到数据收集,再到跨地理位置访问。然而,在配置到手机/电脑等设备时你可能会遇到住宅代理不起作用的情况。这可能是由多种因素造成的,所以让我们来看看可能的原因以及如何处理它们。一、住宅代理不可......
  • 根据网络连接(文件链接)下载文件到本地
    1publicvoidDownloadFile(stringURL,stringfilename)2{3HttpWebRequestreq=null;4HttpWebResponserep=null;5Streamst=null;6Streamso=null;7try8{9req=(HttpWebRequest)Web......