读取配置连接信息,利用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);

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值