Mybatis 动态读取配置文件driver、url、username、username

34 篇文章 0 订阅
2 篇文章 1 订阅

项目的结构:



部署到tomcat的时候,是打成jar包:希望能够从config.xml中取到mybatis的相关配置

DB是sqlserver2016!!!


<?xml version="1.0" encoding="utf-8"?>
<config>
	<sqlserver>
		<db user="sa" pwd="sa" url="jdbc:sqlserver://localhost;Database=test" driver="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
	</sqlserver>
</config>


代码中mybatis配置:




正常情况下只要在db.properties中配好响应的参数即为实现动态配置,但是现在问题是你只能从jar外读取到配置,即从config.xml中取出配置!


以下是具体的解决方案:

①读取配置

/**
	 * 初始化jar的时候动态读取jar包以外的配置文件
	 * 解析的时候自动去掉CDMA
	 * @param xml
	 */
	@SuppressWarnings("unchecked")
	public static DBConfig readXmlConfig(String xml){
		DBConfig config = new DBConfig();
		try { 
			Element root = null;
			SAXBuilder builder = new SAXBuilder();
			File file = new File(xml);
			Document doc = builder.build(file);
			root = doc.getRootElement();
			List<Element> list = root.getChildren("sqlserver");

			if(list!=null&&list.size()>0){
				
				List<Element> list1 = list.get(0).getChildren("db");
				for (Element element : list1) {
					config.setUrl(element.getAttributeValue("url"));
					config.setUser(element.getAttributeValue("user"));
					config.setPassword(element.getAttributeValue("pwd"));
					config.setDriver(element.getAttributeValue("driver"));
				}
			}
		} catch (JDOMException e) {
			e.printStackTrace();
		}  catch (IOException e) {
			e.printStackTrace();
		}catch (Exception e) {
			e.printStackTrace();
		}

		return config;
	}



②赋值到Mybatis

//这里必须要为properties文件中的参数赋值
			Properties properties = new DBProperUtils().properties;

			properties.setProperty("driver", driver);
			properties.setProperty("url", url);
			properties.setProperty("username", username);
			properties.setProperty("password", password);

			OutputStream fos = new FileOutputStream(DBProperUtils.iniPath);
			properties.store(fos,"");  
			fos.close();
			
			String resource = "/mybatis-config.xml";	
			InputStream fis2 = getClass().getResourceAsStream(resource); 

			sqlSessionFactory = new SqlSessionFactoryBuilder().build(fis2,properties);


这里有两处关键的地方,对比一下说明:

对比一:用Resources.getResourceAsReader读取配置文件

String resource = "domain/configuration.xml";  
Reader reader = Resources.getResourceAsReader(resource);  //这样读不要/
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(reader); 


对比二:用流的形式getClass().getResourceAsStream加载

String resource = "/mybatis-config.xml";
InputStream fis2 = getClass().getResourceAsStream(resource); //这样读要/
sqlSessionFactory = new SqlSessionFactoryBuilder().build(fis2,properties);


在研究的时候用流动态赋值了db.properties,然后用对比一的方式加载,一定要项目刷新一下才能更新到,网上搜了很多例子,但都不是我想要的

然后经过领导的点拨后,知道原理,赋值到db.properties用流取出来的时候也用流读取,这个问题就迎刃而解了!


其它延伸问题:

用Mybatis调存储过程,存储过程有两个动作,insert后select,然后用Mybatis跟sqlserver交互,然后发现一个问题,如果mapper中标签是select就只能做select动作,如果是insert,那又只能做insert动作,就是没法两个结果一起执行掉

<select id="test" resultType="ReturnSql">
		 <![CDATA[  
		    {call testSelectAndInsert(
				    #{0,mode=IN,jdbcType=INTEGER},
				    #{1,mode=IN,jdbcType=INTEGER},
				    #{2,mode=IN,jdbcType=INTEGER},
				    #{3,mode=IN,jdbcType=INTEGER},
				    #{4,mode=IN,jdbcType=INTEGER},
				    #{5,mode=IN,jdbcType=VARCHAR},
				    #{6,mode=IN,jdbcType=NVARCHAR},
				    #{7,mode=IN,jdbcType=VARCHAR},
				    #{8,mode=IN,jdbcType=VARCHAR}
			    )
		    }  
		]]>  
	</select>
<insert id="test" resultType="ReturnSql">
		 <![CDATA[  
		    {call testSelectAndInsert(
				    #{0,mode=IN,jdbcType=INTEGER},
				    #{1,mode=IN,jdbcType=INTEGER},
				    #{2,mode=IN,jdbcType=INTEGER},
				    #{3,mode=IN,jdbcType=INTEGER},
				    #{4,mode=IN,jdbcType=INTEGER},
				    #{5,mode=IN,jdbcType=VARCHAR},
				    #{6,mode=IN,jdbcType=NVARCHAR},
				    #{7,mode=IN,jdbcType=VARCHAR},
				    #{8,mode=IN,jdbcType=VARCHAR}
			    )
		    }  
		]]>  
	</insert>

Mybatis用的版本是:mybatis-3.2.0.jar

最终确认问题是:没有关闭!没有关闭!没有关闭!sqlSession.close(); 


/*
	 * 【==测试②==】
	 * Author:xiebin
	 * Comment: 执行insert后,在执行select
	 * Date:2016-11-01
	 * 测试从外部读取mybatis配置文件
	 */
	public Map<String, Object> testInsertAndSelect(){
		Map<String,Object> returnMapObject = new HashMap<String, Object>();
		try
		{
			TransactionManagerDao dao = sqlSession.getMapper(TransactionManagerDao.class);
			Map<String, Object> dataMap = dao.testInsertAndSelect(9545, "谢彬", 1, 1, 1);
					
			returnMapObject.put("ErrorCode", 0);
			returnMapObject.put("data", dataMap);
		}catch(Exception e){
			returnMapObject.put("ErrorCode", ErrorCode.QUERY_EXCEPTION_ERROR);
			returnMapObject.put("ErrorMsg", e);
		}finally {
			sqlSession.close();  
			sqlSession.clearCache();
        }  
		return returnMapObject;
		
	}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值